Skip to main content

Command Palette

Search for a command to run...

JavaScript Using generator function for fibonacci sequence

Updated
•2 min read•View as Markdown

Here's a nice use-case for generator functions.

The following is an implementation of fibonacci sequence of arbitrary size (see https://jsfiddle.net/cj83gkno/). Generator function makes this really easy.

/*
Fibonacci sequence of arbitrary length
0, 1, 1, 2, 3, 5, 8, 13, ...
*/

function* fibonacci() {
    // we need to store both current and next
  let current=0;
  let next=1;

  // infinite loop to generate yields
  while (true) {
      // first extract optional value to next(v)
    // as you will see lalter, this has a function.
    // also, yield current
    const v=yield current;

    [current, next]=[next, next+current];

    // here's why
    // if next(true) is passed then reset sequence.
    if (v) {
      current=0;
      next=1;
    }
  }
}

// let's run it
const seq=fibonacci();
console.log(seq.next());
console.log(seq.next());
console.log(seq.next());
console.log(seq.next());
console.log(seq.next());
console.log(seq.next());
console.log(seq.next());

// reset seq
console.log(seq.next(true));
console.log(seq.next());
console.log(seq.next());

Output

{
  done: false,
  value: 0
}
{
  done: false,
  value: 1
}
{
  done: false,
  value: 1
}
{
  done: false,
  value: 2
}
{
  done: false,
  value: 3
}
{
  done: false,
  value: 5
}
{
  done: false,
  value: 8
}
{
  done: false,
  value: 0
}
{
  done: false,
  value: 1
}
{
  done: false,
  value: 1
}

Firstly, whenever the code execution reaches yield it is paused there until next() is called.

Particular note on const v=yield current;. Here v is the value passed to next(v) and even if the old value of v is already bound when execution is paused, it gets updated to the new v passed to next(v) when execution resumes. So, in if (v) {...}, v is not the old value but the new one passed fresh to next(v).

More from this blog

Linux and Web

31 posts