Your loop can be terminated in a few different ways. You're using a boolean loop
variable, but there are cleaner ways.
One is to simply move the if
condition to the while
condition (Malachi's answer beat me to this):
while (fib[i-1] + fib[i-2] <= max) {
i = fib.push(fib[i-1] + fib[i-2]);
}
push
helpfully returns the array's new length, so you don't need the i++
.
Another is to keep the if
branching, but use it to break
the loop instead:
while (true) {
var next = fib[i-1] + fib[i-2];
if (next > max) {
break; // exit the loop
}
i = fib.push(next);
}
Here we avoid calculating the new fibonacci number twice, but still: the previous code block is probably still the cleanest.
You also initialize i
to 2, which is a bit redundant: It's the length of the fib
array. Rather than manually initializing the array, and manually recording its length, I'd just do var i = fib.length
.
Lastly, it might be good to consider "bad" max values. I.e. what if the maximum is set to zero? Or 1? Or -2324359? For zero you could return an empty array; for 1 you'd need to return a shorter array than what you start with, and for the negative max you could throw an error or return null. Not saying you need to any of this, but it's always to good to consider how you handle such cases.