-
Notifications
You must be signed in to change notification settings - Fork 1
/
sortBy.js
42 lines (38 loc) 路 1.11 KB
/
sortBy.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Returns a copy of the list, sorted by provided key according to the
* comparator function.
*
* Note that this is a copy of the list. It does not modify the original.
*
* @param {String} key .
* @param {Array} list .
* @param {Function} fn .
* @param {Boolean} desc .
* @return {Array} A new list sorted by the keys generated by `fn`.
* @example
*
* const users = [
* { 'user': 'ed', 'age': 36 },
* { 'user': 'fer', 'age': 34 },
* { 'user': 'ivan', 'age': 35 },
* { 'user': 'inma', 'age': 32 }
* ]
*
* sortBy('age', users, parseInt, false)
* // [
* // { 'user': 'inma', 'age': 32 },
* // { 'user': 'fer', 'age': 34 },
* // { 'user': 'ivan', 'age': 35 },
* // { 'user': 'ed', 'age': 36 }
* // ]
*
*/
const baseSortBy = (key, fn, desc = false) => {
const _key = fn ? (x) => fn(x[key]) : (x) => x[key]
desc = !desc ? 1 : -1
return (a, b) => {
return a = _key(a), b = _key(b), desc * ((a > b) - (b > a))
}
}
const sortBy = (key, list, fn, desc = false) => Array.prototype.slice.call(list, 0).sort(baseSortBy(key, fn, desc))
export default sortBy