Skip to content

Instantly share code, notes, and snippets.

@drewlesueur
Created May 30, 2011 14:51
Show Gist options
  • Select an option

  • Save drewlesueur/999005 to your computer and use it in GitHub Desktop.

Select an option

Save drewlesueur/999005 to your computer and use it in GitHub Desktop.
JavaScritp Iterators and Generators

I read up on JavaScript Iterators and Generators today.

https://developer.mozilla.org/en/JavaScript/Guide/Iterators_and_Generators
https://github.com/davidflanagan/javascript6_examples/blob/master/examples/11.01.linesgenerator.js http://wiki.ecmascript.org/doku.php?id=harmony:generators

Here's How they wrote the Fibonacci sequence

function fibonacci(){
  var fn1 = 1;
  var fn2 = 1;
  while (1){
    var current = fn2;
    fn2 = fn1;
    fn1 = fn1 + current;
    yield current;
 }
}

var sequence = fibonacci();
print(sequence.next()); // 1
print(sequence.next()); // 1
print(sequence.next()); // 2
print(sequence.next()); // 3
print(sequence.next()); // 5
print(sequence.next()); // 8
print(sequence.next()); // 13

Here's how I would write it without using yield

var fibonacci = function() {
  var n1 = 0
  var n2 = 1
  return function() {
    var oldn1 = n1
    n1 = n1 + n2
    n2 = oldn1
    return n1
  }
}

sequence = fibonacci()
print(sequence()); // 1
print(sequence()); // 1
print(sequence()); // 2
print(sequence()); // 3
print(sequence()); // 5
print(sequence()); // 8
print(sequence()); // 13

todo: async generators.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment