Skip to content

Instantly share code, notes, and snippets.

@jooyunghan
Last active November 19, 2015 21:20
Show Gist options
  • Save jooyunghan/c7f164b2a70463228d50 to your computer and use it in GitHub Desktop.
Save jooyunghan/c7f164b2a70463228d50 to your computer and use it in GitHub Desktop.
Sum the even values in Fibonacci series which are less than 4000000
> npm install babel-preset-es2015
> npm install babel-polyfill
> babel-node --presets "es2015" evenfib.js
4613732
const iterate = function* (init, fn) {
yield init;
yield* iterate(fn(init), fn);
}
const map = function (fn, gen) {
function* inner(gen) {
for (const x of gen) {
yield fn(x);
}
}
return (gen === void 0) ? inner : inner(gen);
}
const filter = function (fn, gen) {
function* inner(gen) {
for (const x of gen) {
if (fn(x))
yield x;
}
}
return (gen === void 0) ? inner : inner(gen);
}
const takeWhile = function (fn, gen) {
function* inner(gen) {
for (const x of gen) {
if (fn(x))
yield x;
else
break;
}
}
return (gen === void 0) ? inner : inner(gen);
}
const reduce = function (fn, gen) {
function inner(gen) {
const {value, done} = gen.next();
if (done) return void 0;
function rec(acc) {
const {value, done} = gen.next();
if (done) return acc;
return rec(fn(acc, value));
}
return rec(value);
}
return gen === void 0 ? inner : inner(gen);
}
function* fib() {
yield* map(x => x[0])(iterate([0,1], ([a,b]) => [b, a+b]));
}
function compose(...fs) {
return fs.reduce((f,g) => (x => f(g(x))));
}
const add = (a,b) => a + b;
const sum = reduce(add);
const even = x => x%2 === 0;
const lessThan = limit => x => x < limit;
function evenFibonacciSum() {
return compose(sum, filter(even), takeWhile(lessThan(4000000)))(fib());
}
console.log(evenFibonacciSum());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment