HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

How would you count in the Fibonacci Sequence?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theyoufibonaccisequencewouldhowcount

Problem

I was wondering if I did this in a remotely acceptable way:

var fib = function(params) {
    var iterations = params;
    var output = [0];

    for(var i = 1, j = 1; j < iterations; j++){
        //i is the fibonacci sequence
        //j counts iterations
        output.push(i);
        i = parseInt(output[j]) + parseInt(output[j-1]);

    }
        console.log(output[iterations-1]);
}

fib("4");


Here the function takes in a parameter (eg 4), then a for loop counts through and adds every Fibonacci number until that iteration to an array (so in this example, 4 values are in the output array).

Mostly I'd just like to know if you guys would reach a similar conclusion and if I did anything that's a huge no-no, particularly using output[iterations-1] to force the counter to be at the same point as the array (due to 0th index) seems iffy.

Solution

var fib = function(params) {
    var iterations = params;


Why are you copying params into iterations, rather than just naming your parameter iterations?

var output = [0];


That's not really your output is it? Perhaps there is a better name?

for(var i = 1, j = 1; j < iterations; j++){
        //i is the fibonacci sequence
        //j counts iterations
        output.push(i);
        i = parseInt(output[j]) + parseInt(output[j-1]);


Output already contains ints. There is no reason to parseInt it. Why don't you directly push on the array rather then storing it in an int? Furthermore, you don't actually need an array, you only need the last two elements.

}
        console.log(output[iterations-1]);


Fix the indent here.
}

fib("4");


Why are you passing a string?

Code Snippets

var fib = function(params) {
    var iterations = params;
var output = [0];
for(var i = 1, j = 1; j < iterations; j++){
        //i is the fibonacci sequence
        //j counts iterations
        output.push(i);
        i = parseInt(output[j]) + parseInt(output[j-1]);
}
        console.log(output[iterations-1]);

Context

StackExchange Code Review Q#52354, answer score: 7

Revisions (0)

No revisions yet.