-
Notifications
You must be signed in to change notification settings - Fork 1
/
sortByAsync.js
63 lines (51 loc) · 1.47 KB
/
sortByAsync.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const { unCurry } = require('./internals/unCurry')
const compareFunction = (a, b) => {
if (a.criterion === Infinity) {
return b.criterion === Infinity ? 0 : 1
}
if (b.criterion === Infinity) {
return -1
}
if (a.criterion === -Infinity) {
return b.criterion === -Infinity ? 0 : -1
}
if (b.criterion === -Infinity) {
return 1
}
if (a.criterion < b.criterion) {
return -1
}
return a.criterion > b.criterion ? 1 : 0
}
module.exports.compareFunction = compareFunction
const getValue = element => element.value
const sortByFn = collection => collection.sort(compareFunction).map(getValue)
const sortByAsync = callback => collection => Promise
.resolve(collection)
.then(resolvedCollection => Promise.all(
resolvedCollection.map((value, index) => Promise
.resolve(value)
.then(resolvedValue => Promise
.resolve(callback(resolvedValue, index, resolvedCollection))
.then(criterion => ({
value: resolvedValue,
criterion,
})))),
))
.then(sortByFn)
/**
* @callback iteratee
* @async
* @param {*} element - The current element in the collection.
* @param {number} [index] - The index of the current element in the collection.
* @param {*[]} [collection] - The collection.
* @return {Promise<*>}
*/
/**
* @async
* @function sortByAsync
* @param {iteratee} callback
* @param {*[]|Promise<*[]>} collection
* @return {Promise<*[]>}
*/
module.exports.default = unCurry(sortByAsync, 2)