Created
May 12, 2016 14:57
-
-
Save robbiemu/10a0144b7ca2d810f5fcc1351f240bef to your computer and use it in GitHub Desktop.
es6 generators
This file contains 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
require('console'); | |
/** | |
* Created by rober_000 on 5/12/2016. | |
*/ | |
class Factorials{ | |
recursive(n){ | |
if (n === 1) { | |
return 1; | |
} | |
return n * this.recursive(n - 1); | |
} | |
generative(n){ | |
var gf = this.inner_generative(n) | |
var intermediate = gf.next(); | |
var final = NaN; | |
while(!intermediate.done){ | |
// you could be doing work here, which is the purpose of a generator | |
final = intermediate.value; | |
intermediate = gf.next(); // next takes a value, but disposes of it. generators must maintain their own stack | |
} | |
return final; | |
} | |
*inner_generative(n){ | |
var sequence = [1] | |
while (n-- > 0) { | |
yield sequence[sequence.length - 1] | |
sequence.push((sequence.length + 1) * sequence[sequence.length - 1]) | |
} | |
} | |
} | |
f = new Factorials(); | |
console.log(f.recursive(5)); | |
console.log(f.generative(5)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment