I want to solve this problem in functional programming (fp) way only.
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
Source: https://projecteuler.net/problem=2
This is my fp approach:
const range = num => Array.from(new Array(num), (_, i) => i);
const divisibleBy = divisor => num => num % divisor === 0;
const isEven = i => divisibleBy(2)(i);
const sum = (acc, val) => acc + val;
const fibonacciOf = n => {
if (n === 0) {
return 1;
}
if (n === 1) {
return 2;
}
return fibonacciOf(n - 1) + fibonacciOf(n - 2);
};
const doUntil = maxVal => (fiboResult, i) => {
const next = i + 1;
return fiboResult >= maxVal ? i : doUntil(maxVal)(fibonacciOf(next), next);
};
const until4Mil = doUntil(4000000);
const maxRange = until4Mil(0, 0);
const solution = range(maxRange)
.map(fibonacciOf)
.filter(isEven)
.reduce(sum);
console.log("solution ", solution);
1) I was struggling with the recursion, because that was the only way I could think of how to emulate the do...while
loop. Do you know any alternative to the do...while
loop (aka. a loop where you don't know when it ends) in fp?
2) Also, I'm not sure whether the part const maxRange = until4Mil(0, 0);
is clean code or not.
Any other improvement suggestions are welcomed as well.