Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

question from:https://stackoverflow.com/questions/17512726/iterating-with-while-loop-instead-of-for-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
98 views
Welcome To Ask or Share your Answers For Others

1 Answer

Would something like this satisfy you?

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...