Ryan
Ryan

Reputation: 6327

Generators in ES6

I have created a function to generate fibonacci series using es6 generators:

//WARNING CAUSES INFINITE LOOP
function* fibonacci(limit = Infinity) {
  let current = 0
  let next = 1

  while (current < limit) {
    yield current
      [current, next] = [next, current + next]
  }
}

for (let n of fibonacci(200)) {
  console.log(n)
}

The above function doesn't swap the two numbers while if done normally in any other function swaps the two. On running this function I get an infinite loop. Why doesn't the variable swap work?

Upvotes: 0

Views: 267

Answers (2)

Bergi
Bergi

Reputation: 664297

You've got a syntax mistake: a missing semicolon makes the engine parse your statement as

yield (current [ current, next ] = [ next, current + next ])
//             ^        ^
// property access    comma operator

If you want to omit semicolons and let them be automatically inserted where ever possible needed, you will need to put one at the begin of every line that starts with (, [, /, +, - or `:

function* fibonacci(limit = Infinity) {
  let current = 0
  let next = 1

  while (current < limit) {
    yield current
    ;[current, next] = [next, current + next]
  }
}

for (let n of fibonacci(200)) {
  console.log(n)
}

Upvotes: 2

David Votrubec
David Votrubec

Reputation: 4156

You have to first swap and then yield. Yield will give control back to the caller, so the method kindad stops executing there..

This will work (tested in Firefox

function* fibonacci(limit = Infinity) {
  let current = 0
  let next = 1

  while (current < limit) {
    [current, next] = [next, current + next];
    yield current;

  }
}

for (let n of fibonacci(200)) {
  console.log(n)
}

Upvotes: -1

Related Questions