tnsaturday tnsaturday - 29 days ago 12
Javascript Question

Recursive version of find()

What i'm trying to do is make a recursive version of find, which takes an array and a test function and returns first element of an array, that passes the test. Lets look at the example:

function isEven(num) { return(num%2 == 0); }
var arr = [1, 3, 5, 4, 2];

function findRecursive(arr, func) {
var p = arr.shift();
if (func(p) == true)
return p;
else
findRecursive(arr, func);
}

findRecursive(arr, isEven);


By some reason i'm getting undefined. But if i change shift to pop on line 5, it correctly returns 2. What causes th problem?

Answer Source

You need to return the value of the recursive call, otherwise you return undefined, the standard return value of a function in Javascript.

} else {
    return findRecursive(arr, func);
    // ^^^
}

You may insert a check for the length of the array, if there is no more element to check. Then you could return undefined intentionally.

function isEven(num) { return num % 2 === 0; }

function findRight(array, fn) {
    if (!array.length) {
        return;
    }

    var p = array.pop();
    return fn(p) ? p : findRight(array, fn);
}

console.log(findRight([1, 3, 5, 4, 2], isEven)); // 2
console.log(findRight([1, 3, 5], isEven));       // undefined