Last active
December 26, 2018 08:34
-
-
Save indongyoo/12c3f49ff8f1ef858ccc735f032f3011 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
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