1

I need to implement a Fibonacci sequence Оthrough a function for my homework. And I need to implement a function so that each subsequent call will output the next number in the sequence. It seems simple if you pass an argument to the function, but I'm not allowed to do that by the assignment. I have implemented this function with an argument, the code is shown below:

function helperFibonacci(n) {
  let number1 = 0;
  let number2 = 1;

  for (i = 0; i < n; i++) {
    let current = number1 + number2;
    number1 = number2;
    number2 = current;
    console.log(current);
  }
}

helperFibonacci(2);

Please help me implement this function without passing an argument. thanks!

5
  • You need to save the state current position in the sequence in a global variable. Commented Dec 16, 2021 at 18:55
  • Instead of saving the position, save number1 and number2. Then you can just update them each time you call. Commented Dec 16, 2021 at 18:56
  • @RandyCasburn That doesn't remember its position between calls. Commented Dec 16, 2021 at 18:56
  • 1
    Does this answer your question? JS Classic Fibonacci Challenge - Differences between two solutions Commented Dec 16, 2021 at 18:59
  • Not part of the question, but I'd output "number2" at the beginning of the loop and remove outputting "current" so that you get the expected repeated "1" at the beginning of the sequence. Commented Dec 16, 2021 at 19:08

5 Answers 5

2

Change number1 and number2 to global variables, and get rid of the loop.

let number1 = 0;
let number2 = 1;

function helperFibonacci() {
  let current = number1 + number2;
  number1 = number2;
  number2 = current;
  console.log(current);
}

for (let i = 0; i < 10; i++) {
  helperFibonacci();
}

Sign up to request clarification or add additional context in comments.

Comments

1

Try with this one , works great , have a good coding :)

 function fib(n) {
 let fibList = [];
 if (n < 2) {
    fibList.push(0);
 } else {
    let prev = 0;
    let curr = 1;
    fibList.push(prev, curr);
    for (let i = 2; i < n; i++) {
        const next = prev + curr;
        prev = curr;
        curr = next;
        fibList.push(curr);
    }
 }
 console.log(fibList);
 }

Comments

1

OPTION 1 USING GENERATOR FUNCTIONS

I think the proper way to do this is to use a Generator function. Theese are functions meant to return sequences, they are built for this kinds of situations where you have a sequence that you can calculate based on a formula and want to get the next value at will.

So lets say you have a simple formula to calculate the nth fibonacci number

function fibonacci(n = 0) {
    if (n < 0){ throw 'Fibonacci not defined for negative numbers'} 
    if (n < 2) { return n};
    return fibonacci(n - 1) + fibonacci(n - 2); 
}

so then you just wrap it in a generator function (using the function* syntax, note the *)

function* fibonacciGenerator() {
  var index = 0;
  while (true){
        // yields the next fibonacci
        yield fibonacci(index++);
    }
}

Then you can use it creating a new generator and calling the next function to retrieve the next element in the sequence. Note the while true here represents that the sequence is infinite, that is that it never ends and I can keep getting more and more elements. This does not become an infinite loop because of the yield keyword

let fibonacciSequence = fibonacciGenerator();
fibonacciSequence.next().value; // 0
fibonacciSequence.next().value; // 1
fibonacciSequence.next().value; // 1
fibonacciSequence.next().value; // 2

You can read more about generator functions here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*

NOT USING GENERATOR FUNCTIONS

If you are not familiar with generator functions or cannot use them, you can do it with a regular function and save the "state". I dont recommend at all saving it in a global variable because its a considered bad practice. But you can create a closure.

Closures are like functions with their own scope, or environment where they can have variables.

function fibonacciGenerator() {
    var index = 0;
    return function () {
        return fibonacci(index++);
    }
}

then use it

let fibonacciSequence = fibonacciGenerator();
fibonacciSequence(); // 0
fibonacciSequence(); // 1
fibonacciSequence(); // 1
fibonacciSequence(); // 2

note that the structure is similar than that of generators, but we have normal functions instead.

You can read more about closures here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

Comments

0

This will return first 10 fibos , as we passed 10 in pramas .

const fiboFun = (length) => {
  let fibos = [];

  for (let i = 0; i < length; i++) {
    if (fibos[i - 2] && fibos[i - 1]) {
      let add = fibos[i - 2] + fibos[i - 1];
      fibos.push(add);
    } else {
      fibos.push(i);
    }
  }
  return fibos;
};

console.log(fiboFun(10));

1 Comment

The questioner wants a solution without passing the arguments. Kindly either edit/update your answer or delete it. Thanks.
0

handling it from the most basic level(basics) :

function fibonacciGenerator (n) {
    let output = []
    if(n === 1){
       output.push(0) 
    }
    else if(n === 2){
        output.push(0)
        output.push(1)
    }
    else if(n > 2){
        output.push(0);
        output.push(1)
        for(let num = 0;num <= n - 3; num++){
            const new_number = output[num] + output[num+1]
            output.push(new_number)
        }
    }
    return output

}
console.log(fibonacciGenerator (4))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.