Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const stoppableReduce = (f, initialValue, collection, cb) => {
- const _collection = collection.slice();
- let stopper = false;
- const iterator = (acc, index, list) => {
- const item = list[index];
- const nextAcc = f(acc, item, () => {
- stopper = true;
- });
- if (stopper || index === (list.length - 1))
- return cb(nextAcc);
- return setImmediate(() => iterator(acc, index + 1, list));
- };
- iterator(initialValue, 0, collection);
- };
- stoppableReduce(
- (acc, item, stopAfterIteration) => {
- item >= 2 && stopAfterIteration();
- return [...acc, item+1 ]
- },
- [],
- [ 0, 1, 2, 3, 4 ],
- console.log
- );
Add Comment
Please, Sign In to add comment