Skip to content

Instantly share code, notes, and snippets.

@hallski
Last active November 13, 2017 20:08
Show Gist options
  • Save hallski/66a5c914d3fbd2e7dda76c608ef0f955 to your computer and use it in GitHub Desktop.
Save hallski/66a5c914d3fbd2e7dda76c608ef0f955 to your computer and use it in GitHub Desktop.
Javascript implementation of `zip` that works with Iterables.
/**
* Uses the `produce` function to produce values until the `predicate` returns false.
* If supplied, each value is transformed by `transform` before being yielded.
*
* @param {Function} produce produces the next value
* @param {Function} predicate return true if the production should continue
* @param {Function} transform transforms the produced value, defaults to identity
*/
function* produceWhile(produce, predicate, transform = value => value) {
while(true) {
const value = produce()
if (predicate(value) === false) {
break
}
yield transform(value)
}
}
/**
* Zip function that zips each value from the supplied arrays. It will stop once
* any of the iterators has been depleted.
*
* @param {Array of Iterables} iterables an array of Iterable objects.
*/
function zip(...iterables) {
const iterators = iterables.map(iterable => iterable[Symbol.iterator]())
const zipper = produceWhile(() => iterators.map(iterator => iterator.next()),
value => value.find(v => v.done) === undefined,
value => value.map(v => v.value))
return [...zipper]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment