Last active
June 11, 2016 19:26
-
-
Save joshwcomeau/41d8a8b7682bf1b6c6378c143031d9e8 to your computer and use it in GitHub Desktop.
Fibonacci Generators
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
////// Fun with ES2015 Generators & Fibonacci Sequence ////// | |
// | |
// Generators are awesome for lazy calculations, but they're less | |
// than ideal for certain use-cases (give me the result of the | |
// 1000th iteration). | |
// | |
// This is an experiment where I try to have my cake and eat it too, | |
// by wrapping a generator with a factory function. | |
// | |
//// Note: This is the comment-free version! | |
//// The fully-annotated, unabridged version is available here: | |
//// https://gist.github.com/joshwcomeau/c26f64232095322a9b3ce1b36b83107b | |
function* fibonacciGenerator() { | |
let previous = 0, current = 1; | |
while (true) { | |
[previous, current] = [current, previous + current]; | |
yield(current); | |
} | |
} | |
function fibonacciFactory(n = 1) { | |
const generator = fibonacciGenerator(); | |
const sequence = [null]; | |
return (n = 1) => { | |
while (typeof sequence[n] === 'undefined') { | |
sequence.push(generator.next().value); | |
} | |
return sequence[n] | |
} | |
} | |
////////////////// Test! ////////////////// | |
const t1Start = performance.now(); | |
const t1Generator = fibonacciGenerator(); | |
for (let i = 0; i < 25; i++) { | |
let sequenceNum = 0; | |
while (sequenceNum <= 1000) { | |
t1Generator.next(); | |
sequenceNum++; | |
} | |
} | |
const t1Time = performance.now() - t1Start; | |
const t2Start = performance.now(); | |
const t2Factory = fibonacciFactory(); | |
for (let i = 0; i < 25; i++) { | |
fibonacciFactory(1000); | |
} | |
const t2Time = performance.now() - t2Start; | |
console.log(`Generator took ${t1Time}ms`); // ~10-20ms | |
console.log(`Factory took ${t2Time}ms`); // 0.01 - 0.2ms | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment