-
-
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
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
/* | |
* 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