-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreduce.js
More file actions
70 lines (54 loc) · 1.8 KB
/
Copy pathreduce.js
File metadata and controls
70 lines (54 loc) · 1.8 KB
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
function handleResult(handleFn) {
return function (result) {
handleFn(result);
};
}
function promisify(value) {
if (value.then) {
return value;
}
return Promise.resolve(value);
}
module.exports = function reduce(collection, callback, accumulator, maxQueueSize, currentQueue, nextItemIndex) {
maxQueueSize = maxQueueSize || 1;
currentQueue = currentQueue || [];
nextItemIndex = nextItemIndex || 0;
return new Promise(function (resolve, reject) {
var lastCollectionIndex = collection.length - 1;
// already iterated over all items in collection
if (nextItemIndex > lastCollectionIndex && currentQueue.length === 0) {
resolve(accumulator);
return;
}
var availableSlots = maxQueueSize - currentQueue.length;
var itemsToAddToQueue = collection.slice(nextItemIndex, nextItemIndex + availableSlots);
currentQueue = currentQueue.concat(
itemsToAddToQueue.map(function (item, i) {
var index = i + nextItemIndex;
var itemPromise = promisify(callback(accumulator, item, index, collection))
.then(function (result) {
return {
item: item,
value: result
};
});
itemPromise.item = item;
return itemPromise;
})
);
if (currentQueue.length === 0) {
resolve(accumulator);
return;
}
Promise.race(currentQueue)
.then(function (result) {
// remove resolved item from queue
currentQueue = currentQueue.filter(function (itemPromise) {
return itemPromise.item !== result.item;
});
return reduce(collection, callback, result.value, maxQueueSize, currentQueue, nextItemIndex + itemsToAddToQueue.length);
})
.then(handleResult(resolve))
.catch(handleResult(reject));
});
};