Last active
April 27, 2018 11:46
-
-
Save violet-athena/26a72392a2e4fc4e0f1f9dc2487d29fc to your computer and use it in GitHub Desktop.
Doing Fibonacci, iterative vs. functional
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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