Skip to content

Instantly share code, notes, and snippets.

@indongyoo
Created December 7, 2018 03:30
Show Gist options
  • Save indongyoo/cd8721d3267eb4371e7d72006bdc4b7e to your computer and use it in GitHub Desktop.
Save indongyoo/cd8721d3267eb4371e7d72006bdc4b7e to your computer and use it in GitHub Desktop.
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