0

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?

Kaiido
  • 87,051
  • 7
  • 143
  • 194
Ryan
  • 1,594
  • 1
  • 7
  • 15

2 Answers2

2

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)
}
Bergi
  • 513,640
  • 108
  • 821
  • 1,164
-1

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)
}
David Votrubec
  • 3,420
  • 1
  • 25
  • 38