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?
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.
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
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.