Guest User

Untitled

a guest
Dec 14th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.63 KB | None | 0 0
  1. const stoppableReduce = (f, initialValue, collection, cb) => {
  2. const _collection = collection.slice();
  3.  
  4. let stopper = false;
  5.  
  6. const iterator = (acc, index, list) => {
  7. const item = list[index];
  8.  
  9. const nextAcc = f(acc, item, () => {
  10. stopper = true;
  11. });
  12.  
  13. if (stopper || index === (list.length - 1))
  14. return cb(nextAcc);
  15.  
  16. return setImmediate(() => iterator(acc, index + 1, list));
  17. };
  18.  
  19.  
  20. iterator(initialValue, 0, collection);
  21. };
  22.  
  23. stoppableReduce(
  24. (acc, item, stopAfterIteration) => {
  25. item >= 2 && stopAfterIteration();
  26.  
  27. return [...acc, item+1 ]
  28. },
  29. [],
  30. [ 0, 1, 2, 3, 4 ],
  31. console.log
  32. );
Add Comment
Please, Sign In to add comment