Wednesday, July 22, 2020

Making a fibonacci generator that can be consumed in functional manner

From https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-odd-fibonacci-numbers

Given a positive integer num, return the sum of all odd Fibonacci numbers that are less than or equal to num.

The first two numbers in the Fibonacci sequence are 1 and 1. Every additional number in the sequence is the sum of the two previous numbers. The first six numbers of the Fibonacci sequence are 1, 1, 2, 3, 5 and 8.

For example, sumFibs(10) should return 10 because all odd Fibonacci numbers less than or equal to 10 are 1, 1, 3, and 5.

sumFibs(1) should return a number.

sumFibs(1000) should return 1785.

sumFibs(4000000) should return 4613732.

sumFibs(4) should return 5.

sumFibs(75024) should return 60696.

sumFibs(75025) should return 135721.

function* fibGenerator(qualifierFunc) {
    let a = 0;
    let b = 1;

    for (;;) {
        if (qualifierFunc && !qualifierFunc(a)) {
            return;
        } 

        yield a;

        [a, b] = [b, a + b];
    }
}

We can solve it this way:
let sum = 0;
let value, done;
const iter = fibGenerator(n => n <= 1000);
while (!({value,done} = iter.next()).done) {
    sum += value % 2 == 1 ? value : 0;
}  

console.log('fib sum', sum);

Output:
fib sum 1785

Or we can do it in functional way:
console.log('fib sum', 
    Array.from(fibGenerator(n => n <= 1000), v => v % 2 === 1 ? v : 0).reduce((a, b) => a + b)
);

Output:
fib sum 1785

One thing that stands out the most on functional programming is that most of the time you don't have to use assignment operations to perform a task. That's one of the hallmarks of functional programming.

No comments:

Post a Comment