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