Last active
November 14, 2022 12:47
-
-
Save jonurry/eb294c4cbe0df5377f11922bdbe727bb to your computer and use it in GitHub Desktop.
5.2 Your own loop (Eloquent JavaScript Solutions)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
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.
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.
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
5.2 Your own loop
Write a higher-order function
loop
that provides something like afor
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.