Skip to content

Instantly share code, notes, and snippets.

@kochmaxence
Last active December 14, 2018 16:27
Show Gist options
  • Save kochmaxence/9e369cefc3f34207a1810e4bd5dc7980 to your computer and use it in GitHub Desktop.
Save kochmaxence/9e369cefc3f34207a1810e4bd5dc7980 to your computer and use it in GitHub Desktop.
An example implementation of reduce with a stop function callable in iterator
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
);
const stoppableReduce = (f, initialValue, collection) => {
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 nextAcc;
return iterator(acc, index + 1, list);
};
const result = iterator(initialValue, 0, collection);
return result;
};
console.log(stoppableReduce(
(acc, item, stopAfterIteration) => {
item >= 2 && stopAfterIteration();
return [...acc, item+1 ]
},
[],
[ 0, 1, 2, 3, 4 ]
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment