I think d.push(f(b)) will never be executed.
Can you help me understand what this code is doing?`
function a(f, d) {
if (d.length > 0) {
var b = d.pop();
a(f, d);
d.push(f(b));
}
}
This is called recursion. A function that calls itself until some condition is met, in this case the condition is the array a is empty. Essentially this function takes a function f and an array a as parameters. If the array is not empty it removes the last index and calls itself again.
This continues to happen until the array is empty and then each recursive call returns and moves on to the next line which calls the function that was passed in initially passing it the array index value it popped and adds the returned result back to the array.
Below is an example of it working. Push is never executed until the array is empty but as long as the array had a length greater than 0 on the first call the push will eventually be executed. If the array was empty nothing happens.
Fiddle: https://jsfiddle.net/3joe4yvz/
function a(f, d) {
if (d.length > 0) {
var b = d.pop();
a(f, d);
d.push(f(b));
}
}
var someArray = [1,2,3];
function addOne (value) {
return value + 1;
}
a(addOne,someArray);
alert(JSON.stringify(someArray));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With