Skip to content

Instantly share code, notes, and snippets.

@jonurry
Last active November 14, 2022 12:47
Show Gist options
  • Select an option

  • Save jonurry/eb294c4cbe0df5377f11922bdbe727bb to your computer and use it in GitHub Desktop.

Select an option

Save jonurry/eb294c4cbe0df5377f11922bdbe727bb to your computer and use it in GitHub Desktop.
5.2 Your own loop (Eloquent JavaScript Solutions)
// 5.2 looping version
function loop(value, test, update, body) {
for (let i = value; test(i); i = update(i)) {
body(i)
}
}
loop(3, n => n > 0, n => n - 1, console.log);
// β†’ 3
// β†’ 2
// β†’ 1
@commodore7

commodore7 commented Apr 20, 2019

Copy link
Copy Markdown

at the third part of the loop update(i),you have to assign it to the varable i like this i=update(i),otherwise the i never gets updated and you got yourself an infinite loop,you can try this code,it crashes and creates an infinite loop.

@Dhaneyl

Dhaneyl commented Mar 1, 2022

Copy link
Copy Markdown

Hey bro, I suggest you add " i = update(i)" at the last part of the iteration, letting it like you wrote up there, will get you on an infinite loop.

@jonurry

jonurry commented Mar 2, 2022

Copy link
Copy Markdown
Author

Thanks, @commodore7 and @Dhaneyl
I obviously never tested that... πŸ˜…

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment