-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathmapReduce.js
61 lines (58 loc) · 1.37 KB
/
mapReduce.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
const isPromise = require('./isPromise')
const __ = require('./placeholder')
const curry4 = require('./curry4')
/**
* @name mapReduceAsync
*
* @synopsis
* ```coffeescript [specscript]
* mapReduceAsync(
* map Map,
* reducer (result any, value any, key string, map)=>Promise|any,
* result any,
* mapEntriesIter Iterator<[key, value]>,
* ) -> Promise<result>
* ```
*/
const mapReduceAsync = async function (
map, reducer, result, mapEntriesIter,
) {
for (const [key, value] of mapEntriesIter) {
result = reducer(result, value, key, map)
if (isPromise(result)) {
result = await result
}
}
return result
}
/**
* @name mapReduce
*
* @synopsis
* ```coffeescript [specscript]
* mapReduce(
* map Map,
* reducer (result any, value any, key string, map)=>Promise|any,
* result any,
* ) -> Promise|result
* ```
*/
const mapReduce = function (map, reducer, result) {
const mapEntriesIter = map.entries()
if (result === undefined) {
const firstIteration = mapEntriesIter.next()
if (firstIteration.done) {
return result
}
result = firstIteration.value[1]
}
for (const [key, value] of mapEntriesIter) {
result = reducer(result, value, key, map)
if (isPromise(result)) {
return result.then(curry4(
mapReduceAsync, map, reducer, __, mapEntriesIter))
}
}
return result
}
module.exports = mapReduce