Even fibonnacci array generation

function fibSum(n) {
    var arr = [];
    
    for(let i = 0; arr.length < n; i++){
      var e = arr[i-2] + arr[i-1]
     arr[i-1] && arr[i-2] ? 
       e % 2 == 0 ? 
        arr.push(e) : arr.push(0)
      : arr.push(1)
                                                                                
    }
     return arr
    
   }

I’m trying to create a fibonacci sequence of a specified length (n) with only the even values in the sequence. If the number is not even, a 0 is added otherwise.
When I use the line

arr.push(e): arr.push(e)

In place of the

arr.push(e) : arr.push(0)

Displayed above, it does the expected and returns the usual fibonacci. However, arr.push(0) seems to return an array of 0s and 1s?

You have a bunch of issues going on here.

  1. You should not use var. Use only const or let.

  2. A ternary is not a replacement for an if statement. Do not use a ternary here.

function fibSum(n) {
    const arr = [];
    
    for (let i = 0; arr.length < n; i++) {
      const e = arr[i-2] + arr[i-1];

/* I honestly have no idea what this should do, but you should
    use a proper if statement - a ternary is not the same thing

     if (.... condition ....) {
       // Do this
     } else {
      // Do that
     }
*/
     arr[i-1] && arr[i-2] ? 
       e % 2 == 0 ? 
        arr.push(e) : arr.push(0)
      : arr.push(1)
                                                                                
  }
  return arr
}

You cannot correctly create the even Fibbonaci numbers without creating the odd values as well, so you will need to rethink your approach.

2 Likes

Yeah it just clicked on me that obviously the odd integers are needed to produce the fibonacci. Clumsy error, thank you very much.
Also the arr[i-1] && arr[i-2] is to catch out the initial operations and just add the two 1s a fibonacci starts with

Yeah… that’s not what ternary expressions are for.

As a rule of thumb, if you aren’t using the return value of the ternary expression, then you shouldn’t be using a ternary there.

I see. Why is this? Also, just to confirm, my second use of a ternary operator is valid correct?

Different tools for different jobs.

You can force syntax to do all sorts of unintuitive things, but using the correct syntax/tool for the task help others (and you in 6 months) understand what your code is supposed to do.

A ternary is for setting a different value based upon a condition. An if statement is for executing different logic based upon a condition.

So no, the part where you push (execute logic) is not correct usage of a ternary.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.