ranked

0.4.0 • Public • Published

Build Status Coverage Status NPM Downloads NPM Version Dependencies License

Strategies to assign ranks

In most cases, a sorting function is a best tool to make a ranking. But how about tie scores? You may end up with giving different ranks for tie scores. And I'm quite sure that will make your users dissatisfied.

Solution? You are on the right page.

This module provides various ranking strategies to assign correct ranks to tie scores. It comes with 5 most common strategies: competition, modified-competition, dense, ordinal, and fractional.

Installation

npm install ranked

Usage

Suppose we want to rank an array of computer languages by the year they were introduced.

const languages = [
  { name: 'Javascript', year: 1995 },
  { name: 'Java', year: 1995 },
  { name: 'C#', year: 2001 },
  { name: 'Groovy', year: 2003 },
  { name: 'Scala', year: 2003 },
  { name: 'Go', year: 2009 },
];

We need to provide a function allowing to access the attribute to rank on (the year in this case). The function must accept one item of the array and return the value of the field to rank on.

const scoreFn = language => language.year;

Let's run the ranking operation on this list of languages

var ranked = require('ranked');
var rankedItems = ranked.ranking(languages, scoreFn);

The rankedItems is an array that looks like below. By default, it sorts by descending order, using the competition strategy, and starts ranking at 1

[ { rank: 1, item: { name: 'Go', year: 2009 } },
  { rank: 2, item: { name: 'Groovy', year: 2003 } },
  { rank: 2, item: { name: 'Scala', year: 2003 } },
  { rank: 4, item: { name: 'C#', year: 2001 } },
  { rank: 5, item: { name: 'Javascript', year: 1995 } },
  { rank: 5, item: { name: 'Java', year: 1995 } } ]

To change the ranking strategy, use the third optional parameter.

var rankedItems = ranked.ranking(items, scoreFn, { strategy: 'dense' });

To sort in ascending order

var rankedItems = ranked.ranking(items, scoreFn, { reverse: true });

To start ranking at any number (e.g. 5)

var rankedItems = ranked.ranking(items, scoreFn, { start: 5 });

License

MIT

Dependents (0)

Package Sidebar

Install

npm i ranked

Weekly Downloads

46

Version

0.4.0

License

MIT

Unpacked Size

19.4 kB

Total Files

10

Last publish

Collaborators

  • quocvu