Skip to content

Instantly share code, notes, and snippets.

@indongyoo
Last active December 26, 2018 08:34
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/12c3f49ff8f1ef858ccc735f032f3011 to your computer and use it in GitHub Desktop.
Save indongyoo/12c3f49ff8f1ef858ccc735f032f3011 to your computer and use it in GitHub Desktop.
function f1(max) {
let i = -1, total = 0;
while (true) {
let a = ++i;
a = a * a;
if (!(a < max)) break;
total += a;
}
return total;
}
log(f1(10), f1(20), f1(30)); // 14 30 55
const f2 = max =>
reduce((a, b) => a + b,
takeWhile(a => a < max,
map(a => a * a,
infinity())));
log(f2(10), f2(20), f2(30)); // 14 30 55
function *infinity(i = 0) {
while (true) yield i++;
}
function *takeWhile(f, iter) {
for (const a of iter) {
if (!f(a)) return;
yield a;
}
}
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;
}
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment