-
Notifications
You must be signed in to change notification settings - Fork 1
/
groupByAsync.js
42 lines (36 loc) · 1.02 KB
/
groupByAsync.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
const mapAsync = require('./mapAsync').default
const { unCurry } = require('./internals/unCurry')
const {
resolveCollectionAndValues,
} = require('./internals/resolveCollectionAndValues')
const groupFn = ([collection, keys]) => collection.reduce((acc, cur, i) => {
const key = keys[i]
if (Object.prototype.hasOwnProperty.call(acc, key)) {
acc[key].push(cur)
} else {
acc[key] = [cur]
}
return acc
}, {})
const groupByAsync = callback => collection => Promise
.all([
resolveCollectionAndValues(collection),
mapAsync(callback, collection),
])
.then(groupFn)
/**
* @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<string>}
*/
/**
* @async
* @function groupByAsync
* @param {iteratee} callback
* @param {*[]|Promise<*[]>} collection
* @return {Promise<Object>}
*/
module.exports.default = unCurry(groupByAsync, 2)