-
Notifications
You must be signed in to change notification settings - Fork 1
/
sort-by.js
48 lines (46 loc) · 1.22 KB
/
sort-by.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
43
44
45
46
47
48
/**
* Sort an array of objects by a custom field
*
* @tag Array
* @signature ( field: string, direction: string ) => ( source: Array ): Array
*
* @param {string} field Sort field name
* @param {string} direction Sort direction
* @param {Array} source Input array
*
* @return {Array}
*
* @example
* sortBy( "position" )( [
* { id: 1, position: 3 },
* { id: 2, position: 2 },
* { id: 3 },
* { id: 4, position: 5 },
* { id: 5, position: null },
* ] )
* // [
* // { id: 2, position: 2 },
* // { id: 1, position: 3 },
* // { id: 4, position: 5 },
* // { id: 5, position: null },
* // { id: 3 },
* //]
*/
module.exports = (field, direction = "asc") => source => {
const result = [...source]
const valueIfFieldMissing =
direction === "asc" ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY
return result.sort((alice, bob) => {
const aliceValue = alice[field] || valueIfFieldMissing
const bobValue = bob[field] || valueIfFieldMissing
return alice[field] === null && typeof bob[field] === "undefined"
? -1
: aliceValue < bobValue
? direction === "asc"
? -1
: 1
: direction === "asc"
? 1
: -1
})
}