javascriptecmascript-6

Iterating with while loop instead of for loop


ECMAScript 6 introduces generators, iterators and syntax sugar for iteration. Node.JS v0.11.4 with the flags

--harmony --use_strict --harmony_generators

understands the following generator

function* fibonacci() {
  let previous = 0;
  let current = 1;

  while(true) {
    let temp = previous;
    previous = current;
    yield current = temp + current;
  }
}

I can then print the Fibonacci numbers less than 1000.

for(let value of fibonacci()) {
    if(value > 1000) { break; }
    console.log(value);
}

For this example a while loop instead of a for loop would be more natural, similar to

while(value of fibonacci() < 1000) {
    console.log(value);
}

Can iteration of iterators be done with a while loop instead of a for loop?


Solution

  • You can call a generator step by step using next function

    var sequence = fibonacci();
    var value;
    while ((value = sequence.next()) < 1000) {
        console.log(value);
    }
    

    plus, maybe even a nicer solution would be something like:

    function* fibonacci(limit){
      let previous = 0;
      let current = 1;
    
      while(previous + current < limit) {
        let temp = previous;
        previous = current;
        yield current = temp + current;
      }
    }
    
    for(let value of fibonacci(1000)) {
        console.log(value);
    }