Skip to content

Instantly share code, notes, and snippets.

@eNV25
Forked from jfairbank/fibonacci-generator.js
Last active May 17, 2021 07:35
Show Gist options
  • Save eNV25/531f9b74a6aaec2bb332118bf9d9a26d to your computer and use it in GitHub Desktop.
Save eNV25/531f9b74a6aaec2bb332118bf9d9a26d to your computer and use it in GitHub Desktop.
Fibonacci ES6 Generator
export function *fibonacci(n) {
const infinite = !n && n !== 0;
let current = 0n;
let next = 1n;
while (infinite || n--) {
yield current;
[current, next] = [next, current + next];
}
}
#!/usr/bin/env -S deno run
"use strict";
import { fibonacci } from "https://gist.github.com/eNV25/531f9b74a6aaec2bb332118bf9d9a26d/raw/fibonacci-generator.js";
console.log([...fibonacci(Deno.args[0] || 10)].join(", "))
export function *fibonacci(n, current = 0n, next = 1n) {
if (n === 0) {
return current;
}
yield current;
yield *fibonacci(--n, next, current + next);
}
console.log([...fibonacci(10)]);
// [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment