Skip to content

Instantly share code, notes, and snippets.

@jfairbank
Last active December 4, 2023 12:23
Show Gist options
  • Select an option

  • Save jfairbank/8d36e4bde9c16dc0bac7 to your computer and use it in GitHub Desktop.

Select an option

Save jfairbank/8d36e4bde9c16dc0bac7 to your computer and use it in GitHub Desktop.

Revisions

  1. jfairbank revised this gist Jun 17, 2015. 3 changed files with 14 additions and 5 deletions.
    6 changes: 1 addition & 5 deletions fibonacci-generator.js
    Original file line number Diff line number Diff line change
    @@ -7,8 +7,4 @@ function *fibonacci(n) {
    yield current;
    [current, next] = [next, current + next];
    }
    }

    let [...first10] = fibonacci(10);
    console.log(first10);
    // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
    }
    10 changes: 10 additions & 0 deletions recursive-fibonacci-generator.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    function *fibonacci(n = null, current = 0, next = 1) {
    if (n === 0) {
    return current;
    }

    let m = n !== null ? n - 1 : null;

    yield current;
    yield *fibonacci(m, next, current + next);
    }
    3 changes: 3 additions & 0 deletions usage.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,3 @@
    let [...first10] = fibonacci(10);
    console.log(first10);
    // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
  2. jfairbank revised this gist Jun 17, 2015. 1 changed file with 3 additions and 1 deletion.
    4 changes: 3 additions & 1 deletion fibonacci-generator.js
    Original file line number Diff line number Diff line change
    @@ -9,4 +9,6 @@ function *fibonacci(n) {
    }
    }

    let [...first10] = fibonacci(10);
    let [...first10] = fibonacci(10);
    console.log(first10);
    // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
  3. jfairbank created this gist Jun 17, 2015.
    12 changes: 12 additions & 0 deletions fibonacci-generator.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,12 @@
    function *fibonacci(n) {
    const infinite = !n && n !== 0;
    let current = 0;
    let next = 1;

    while (infinite || n--) {
    yield current;
    [current, next] = [next, current + next];
    }
    }

    let [...first10] = fibonacci(10);