Last active
May 30, 2019 09:11
-
-
Save rusintez/a7fe4457c216c65b5fde8ffa387c5221 to your computer and use it in GitHub Desktop.
sort array by multiple values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* sort array (of objects) by multiple values | |
*/ | |
function sort (order) { | |
return function by (head, ...tail) { | |
return function comparator (a, b) { | |
if (!head) return 0; | |
if (a[head] > b[head]) return order; | |
if (a[head] < b[head]) return -order; | |
head = tail.shift(); | |
return comparator(a, b); | |
} | |
} | |
} | |
function sortMultiple (head, ...tail) { | |
let order = 1; | |
if (head.startsWith("-")) { | |
order = -1; | |
head = head.substr(1); | |
} | |
return function comparator (a, b) { | |
if (!head) return 0; | |
if (a[head] > b[head]) return order; | |
if (a[head] < b[head]) return -order; | |
return sortMultiple(...tail)(a, b); | |
} | |
} | |
const asc = sort(1); | |
const desc = sort(-1); | |
const parse = (str) => sortMultiple(...str.split(' ')); | |
/** | |
* Usage | |
*/ | |
// const { asc, desc } = require('./sort-by'); | |
[{ a: 1, b: 2 }, { a: 1, b: 1 }].sort(asc('a', 'b')); // [{ a: 1, b: 1 }, { a: 1, b: 2 }] | |
[{ a: 1, b: 2 }, { a: 1, b: 1 }].sort(desc('a', 'b')); // [{ a: 1, b: 2 }, { a: 1, b: 1 }] | |
[{ a: 1, b: 2 }, { a: 1, b: 1 }].sort(parse('a -b')); // [{ a: 1, b: 2 }, { a: 1, b: 1 }] | |
[{ a: 1, b: 2 }, { a: 1, b: 1 }].sort(parse('a b')); // [{ a: 1, b: 1 }, { a: 1, b: 2 }] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment