Skip to content

Instantly share code, notes, and snippets.

@violet-athena
Last active April 27, 2018 11:46
Show Gist options
  • Save violet-athena/26a72392a2e4fc4e0f1f9dc2487d29fc to your computer and use it in GitHub Desktop.
Save violet-athena/26a72392a2e4fc4e0f1f9dc2487d29fc to your computer and use it in GitHub Desktop.
Doing Fibonacci, iterative vs. functional
// imperative
function fibonacci(n, first = 0, second = 1) {
while (n !== 0) {
console.log(first); // side-effect
[n, first, second] = [n - 1, second, first + second]; // assignment
}
}
fibonacci(10);
// functional
const fibonacci = (n, first = 0, second = 1) => n === 0
? ""
: first + "\n" + fibonacci(n - 1, second, first + second);
console.log(fibonacci(10))
// array with generators
function* fibonacci(n, first = 0, second = 1) {
while (n !== 0) {
yield first;
[n, first, second] = [n - 1, second, first + second] // assignment
}
}
console.log([...fibonacci(10)]);
// array functional style
const fibonacci = (n, first = 0, second = 1) => n === 0
? []
: [first].concat(fibonacci(n - 1, second, first + second));
console.log(fibonacci(10));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment