Created
December 7, 2018 03:30
-
-
Save indongyoo/cd8721d3267eb4371e7d72006bdc4b7e to your computer and use it in GitHub Desktop.
This file contains hidden or 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 log = console.log; | |
const isIterable = a => !!(a && a[Symbol.iterator]); | |
function *flatten(iter) { | |
for (const a of iter) { | |
if (isIterable(a)) for (const b of a) yield b; | |
else yield a; | |
} | |
} | |
function *map(f, iter) { | |
for (const a of iter) yield f(a); | |
} | |
const flatMap = (f, iter) => flatten(map(f, iter)); | |
log([...flatten([[1, 2], [3, 4]])]); | |
// [1, 2, 3, 4] | |
log([...flatMap(a => [a, a], [1, 2, 3])]); | |
// [1, 1, 2, 2, 3, 3] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment