-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
75 lines (75 loc) · 2.1 KB
/
index.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
64
65
66
67
68
69
70
71
72
73
74
75
/**
* Asynchronously process a list of items, consecutively.
*
* @param Array array
* @param Function(value, index, array) iteratee
*
* @return Promise resolve when done, reject on first error
* @version 1.0.4
*/
export function forEach(array, iteratee) {
const { length } = array;
let index = -1;
return Promise.resolve()
.then(function _proc() {
++index;
if (index < length) {
return Promise.resolve(iteratee.call(array, array[index], index, array))
.then(_proc);
}
});
}
/**
* Asynchronously map a list of items, consecutively.
*
* @param Array array
* @param Function(value, index, array, prevValue) iteratee
* @param any firstValue The `prevValue` of first call to iteratee
*
* @return Promise(array) array mapped, reject on first error
* @version 1.0.4
*/
export function map(array, iteratee, firstValue) {
const result = [];
const { length } = array;
let index = -1;
return Promise.resolve(firstValue)
.then(function _proc(prevValue) {
if (index >= 0) {
result[index] = prevValue;
}
++index;
if (index < length) {
return Promise.resolve(iteratee.call(array, array[index], index, array, prevValue))
.then(_proc);
}
return result;
});
}
/**
* Asynchronously reduce a list of items, consecutively.
*
* @param Array array
* @param Function(accumulator, currentValue, index, array) reducer
* @param any initialValue
*
* @return Promise(any) resolve to the last returned value when done, reject on first error
* @version 1.0.4
*/
export function reduce(array, reducer, initialValue) {
const { length } = array;
let index = -1;
if (arguments.length < 3) {
initialValue = array[0];
++index;
}
return Promise.resolve(initialValue)
.then(function _proc(accumulator) {
++index;
if (index < length) {
return Promise.resolve(reducer.call(array, accumulator, array[index], index, array))
.then(_proc);
}
return accumulator;
});
}