Skip to content

Instantly share code, notes, and snippets.

@indongyoo
Last active December 6, 2018 05:22
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 indongyoo/2bba6bc40d9894fd9374d68fbfb9759d to your computer and use it in GitHub Desktop.
Save indongyoo/2bba6bc40d9894fd9374d68fbfb9759d to your computer and use it in GitHub Desktop.
function reduce(f, acc, iter) {
if (arguments.length == 2) {
iter = acc[Symbol.iterator]();
acc = iter.next().value;
}
for (const a of iter) acc = f(acc, a);
return acc;
}
function *map(f, iter) {
for (const a of iter) yield f(a);
}
function *filter(f, iter) {
for (const a of iter) if (f(a)) yield a;
}
const add = (a, b) => a + b;
const list = [-1, 2, -3, 4];
reduce(add, map(Math.abs, list));
// 10
reduce(add, filter(a => a % 2, map(Math.abs, list)));
// 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment