Skip to content

Instantly share code, notes, and snippets.

@rusintez
Last active May 30, 2019 09:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rusintez/a7fe4457c216c65b5fde8ffa387c5221 to your computer and use it in GitHub Desktop.
Save rusintez/a7fe4457c216c65b5fde8ffa387c5221 to your computer and use it in GitHub Desktop.
sort array by multiple values
/**
* 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