Skip to content

Instantly share code, notes, and snippets.

@iso2022jp
Created July 6, 2021 15:39
Show Gist options
  • Save iso2022jp/12a0fea671dea7d604608b2faa3f045d to your computer and use it in GitHub Desktop.
Save iso2022jp/12a0fea671dea7d604608b2faa3f045d to your computer and use it in GitHub Desktop.
Compute ranks
const ranks = (values, comparator = (a, b) => b - a) => values
.map((value, i) => [value, i])
.slice().sort(([a], [b]) => comparator(a, b))
.reduce((ranks, [value, i], rank, ordered) => [
...ranks.slice(0, i),
rank && !comparator(value, ordered[rank - 1][0]) ? ranks[ordered[rank - 1][1]] : rank + 1,
...ranks.slice(i + 1),
], Array.from({length: values.length}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment