Fibonacci sequecne help

In both cases you return previous + current, so the final return value is always the same.

You could

A) update the return value

Or

B) never add the extra element in the first place

You should not mutate the arry that you are using reduce on. That’s an antipattern.

Okay.
I have reworked it a bit like this:

   if (filtered.slice(-1)[0] > num) {
    filtered.pop();
  }

  const summ = filtered.reduce((previousValue, currentValue) => {
    return previousValue + currentValue;
  })
  return summ;
}

hope it’s better

If you’re gonna have to pop off the last value, why not just never push it in the first place?

1 Like
  while (y <= num) {
    x = arr.slice(-2);
    y = x[0] + x[1];
    arr.push(y);
  }

because of this, it would push the number that I don’t want

Then modify it so it doesn’t.

I would understand if the array were provided to you and you had no control over it, but you wrote the code that makes the array… So, modify the code that pushes so that it checks if it needs to push or not, or breaks from the loop before pushing unnecessarily, or whatever.

1 Like

That was my solution, I couldn’t think of anything else.
I haven’t touched break much in the curriculum here or used it on my own.
I’ll try to see where I can fit break in instead of the IF.

Question, what’s so bad about the IF anyway? is it for speed? and if is how faster is it really?

edit: if (y > num) {break;} I added this inside my while loop instead of the IF, is it better writing the code like this? should you avoid if , if not necessary?

In general, you shouldn’t do work you don’t have to do. You calculated an extra number only to remove it, which means that you are doing extra work.

You don’t need to add a break. You can adjust your loop bounds to avoid adding the extra number.

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