Last active
December 14, 2018 16:27
-
-
Save kochmaxence/9e369cefc3f34207a1810e4bd5dc7980 to your computer and use it in GitHub Desktop.
An example implementation of reduce with a stop function callable in iterator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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