Skip to content

Instantly share code, notes, and snippets.

@suissa
Forked from lubien/imap.js
Created June 23, 2017 19:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suissa/5e8c211a269ea12a5522d24238917b22 to your computer and use it in GitHub Desktop.
Save suissa/5e8c211a269ea12a5522d24238917b22 to your computer and use it in GitHub Desktop.
Proof of concept that you can map multiple functions with only one iteration in JavaScript using iterators (like in Python). Run https://repl.it/Izou/0
/*
* imap lazily maps an interable.
* @param fn Map function
* @param arrOrIterator Either an array or an iterator
*
* It works by always returning a new iterator so that
* you can chain other imaps without loopin once more
* over the same array!
*
* Since iterables are returned, to start the real mapping
* you should do [...it] or use the function `list` I've made.
*/
const imap = (fn, arrOrIterator) => ({
[Symbol.iterator]: () => {
const it = arrOrIterator.next
? arrOrIterator
: arrOrIterator[Symbol.iterator]()
return {
next() {
const {done, value} = it.next()
return {done, value: done ? value : fn(value)}
}
}
}
})
const double = x => 2 * x
const square = x => x * x
const list = it => [...it]
list(
imap(square,
imap(double,[1, 2, 3, 4])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment