Skip to content

Instantly share code, notes, and snippets.

@jonurry
Last active November 14, 2022 12:47
Show Gist options
  • Save jonurry/eb294c4cbe0df5377f11922bdbe727bb to your computer and use it in GitHub Desktop.
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
@jonurry
Copy link
Author

jonurry commented Feb 20, 2018

5.2 Your own loop

Write a higher-order function loop that provides something like a for loop statement. It takes a value, a test function, an update function, and a body function. Each iteration, it first runs the test function on the current loop value and stops if that returns false. Then it calls the body function, giving it the current value. And finally, it calls the update function to create a new value and starts from the beginning.

When defining the function, you can use a regular loop to do the actual looping.

@commodore7
Copy link

commodore7 commented Apr 20, 2019

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
Copy link

Dhaneyl commented Mar 1, 2022

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
Copy link
Author

jonurry commented Mar 2, 2022

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