I just solved this Fibonacci challenge from Project Euler, but I would like to optimize it so that the loop stops before exceeding the argument n. For example if n is 10, I want the fibs array to be [ 1, 1, 2, 3, 5, 8], but having the if (fibs[i + 2] > n) condition in place makes the loop reach the exceeding value and break after that. Which I guess makes sense, but how do I stop it before it exceeds n?
function fiboEvenSum(n) {
let fibs = [1, 1]
for (let i = 0; i <= n; i++) {
fibs[i + 2] = fibs[i] + fibs[i + 1]
if (fibs[i + 2] > n) {
break
}
}
console.log(fibs)
return fibs.filter(a => a % 2 === 0 && a <= n).reduce((a, b) => a + b)
}
No, you don’t. You can use a while loop to create the sequence instead. breaking early on purpose is an indication that you are using the wrong type of loop.
You also don’t need an array of the Fibs, but that’s a more extensive update.