Skip to content

Instantly share code, notes, and snippets.

@robbiemu
Created May 12, 2016 14:57
Show Gist options
  • Save robbiemu/10a0144b7ca2d810f5fcc1351f240bef to your computer and use it in GitHub Desktop.
Save robbiemu/10a0144b7ca2d810f5fcc1351f240bef to your computer and use it in GitHub Desktop.
es6 generators
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