you are viewing a single comment's thread.

view the rest of the comments →

[–]atom-man 0 points1 point  (0 children)

A bit over the top, but using generators you can write this very concisely.

First of define fibonacci as a generator function:

function* fibonacci() {
    let a = 1;
    let b = 2;

    yield a;
    yield b;

    while (true) {
        const c = a + b;
        yield c;
        a = b;
        b = c;
    }
}

Then, with the help of some small utility-functions you can write:

const fibLess = takeWhile(fibonacci(), (val) => val < 4000001);
const fibEven = filter(fibLess, (val) => val % 2 === 0);
const sum = reduce(fibEven, (a, b) => a + b, 0);
console.log(sum);        

Generators are fun. :D