I really did overflow the stack on my first try, but then I put the return statement (see comment in code) without an argument and it worked.
Task:
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.
I didn't use loop.
Book Solution
function loop(start, test, update, body) {
for (let value = start; test(value); value = update(value)) {
body(value);
}
}
loop(3, n => n > 0, n => n - 1, console.log);
// → 3
// → 2
// → 1
My Solution (kept my original function parameter names)
function loop(value, test, update, execute){
if (test(value)) execute(value);
else return // prevents stack overflow?
return loop(update(value),test,update,execute)
}
loop(3, n => n > 0, n => n - 1, console.log);
// → 3
// → 2
// → 1
Did I just made the console output the same thing, or will my solution do the same thing in a real-environment program?
I ask, because I'm not sure if I actually solved it with recursion, or just made the console output the same thing. This will help me feel better about myself, since I'm a noob JS learner. Thanks! :)