Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive call of a function does not get executed

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));
    }
}
like image 226
bmah Avatar asked Feb 07 '26 00:02

bmah


1 Answers

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));
like image 72
AtheistP3ace Avatar answered Feb 12 '26 04:02

AtheistP3ace