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
139k15 gold badges266 silver badges333 bronze badges
asked Nov 2, 2017 at 11:42

2 Answers 2

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)
}
answered Nov 2, 2017 at 12:01
Sign up to request clarification or add additional context in comments.

1 Comment

We should only allow people who understand ASI to omit semicolons :D
-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)
}
answered Nov 2, 2017 at 11:58

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.