1 | import { comparator, curry, either, lt, map, prop, reduce, sort } from 'ramda';
|
---|
2 |
|
---|
3 | /**
|
---|
4 | * Sort a list of objects by a list of props (if first prop value is equivalent, sort by second, etc).
|
---|
5 | *
|
---|
6 | * @func sortByProps
|
---|
7 | * @memberOf RA
|
---|
8 | * @since {@link https://char0n.github.io/ramda-adjunct/2.26.0|v2.26.0}
|
---|
9 | * @category List
|
---|
10 | * @sig [k] -> [{k: v}] -> [{k: v}]
|
---|
11 | * @param {Array.<string>} props A list of properties in the list param to sort by
|
---|
12 | * @param {Array.<object>} list A list of objects to be sorted
|
---|
13 | * @return {Array.<object>} A new list sorted by the properties in the props param
|
---|
14 | * @example
|
---|
15 | *
|
---|
16 | * sortByProps(['num'], [{num: 3}, {num: 2}, {num: 1}])
|
---|
17 | * //=> [{num: 1}, {num: 2} {num: 3}]
|
---|
18 | * sortByProps(['letter', 'num'], [{num: 3, letter: 'a'}, {num: 2, letter: 'a'} {num: 1, letter: 'z'}])
|
---|
19 | * //=> [ {num: 2, letter: 'a'}, {num: 3, letter: 'a'}, {num: 1, letter: 'z'}]
|
---|
20 | * sortByProps(['name', 'num'], [{num: 3}, {num: 2}, {num: 1}])
|
---|
21 | * //=> [{num: 1}, {num: 2}, {num: 3}]
|
---|
22 | */
|
---|
23 |
|
---|
24 | const sortByProps = curry((props, list) => {
|
---|
25 | const firstTruthy = ([head, ...tail]) => reduce(either, head, tail);
|
---|
26 | const makeComparator = (propName) =>
|
---|
27 | comparator((a, b) => lt(prop(propName, a), prop(propName, b)));
|
---|
28 | return sort(firstTruthy(map(makeComparator, props)), list);
|
---|
29 | });
|
---|
30 |
|
---|
31 | export default sortByProps;
|
---|