Snippet - Yet Another Fibonacci Function, but with a JavaScript Generator

5 years ago

To consume a generator, or any iterator for that matter, you can use one of the following three methods:

  • for...of - Loops through values
  • next() - Returns an object with a value and done property. One you get to the last value, done will be true and value will be omitted.
  • Spread operator - Spreads the values which you can collect into an Array.

Code

function * getFibonacci (max = Number.MAX_SAFE_INTEGER) {
    let current = 1
    let previous = 0
    while (current <= max) {
        [current, previous] = [previous, current + previous]
        if (current <= max) {
            yield current
        } else {
            return
        }
    }
}

Consuming with for...of

const forOfTest = getFibonacci(50)
for (let x of forOfTest) {
    console.log(x)
}

Consuming with next()

const nextTest = getFibonacci(50)
for (let x = 0; x < 11; x++) {
    console.log(nextTest.next())
}

Consuming with a Spread Operator

const [...spreadTest] = getFibonacci(50)
spreadTest.forEach(x => console.log(x))

Results

// for...of
0, 1, 1, 2, 3, 5, 8, 13, 21, 34

// next()
{
    "value": 0,
    "done": false
}
{
    "value": 1,
    "done": false
}
{
    "value": 2,
    "done": false
}
// more stuff here...
{
    "done": true
}

// Spread operator
0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Source Code
Discuss on Twitter