I was posed a question during an interview that has left me scratching my head. Rather than spend the weekend worrying about the results, I wanted to try to solve the problem, but I can't figure it out:
Using the below reduce function, build a filter function that takes an array and a test function as arguments, and returns a new array that has filtered the elements of the previous array based on the test function.
This would be simple with using forEach or similar but the requirements were to use this reduce function:
function reduce(array, combine, start) {
var current = start;
for (var i = 0; i < array.length; i++)
current = combine(current, array[i]);
return current;
}
So
var myArray = [0, 1, 3, 5, 9];
console.log(filter(myArray,function(x){
return x > 2;
}));
would return
[3,5,9]
I tried the below but I'm getting an illegal return statement and I'm not even sure I'm going down the right path here.
function filter(array, test){
var giveArray = [];
if(reduce(array,function(current,start){
return test(current);
},false)){
giveArray.push(current);
}
}
return giveArray;
}
Array.prototype.filter?function bigEnough(x) { return x > 2; };/var myArray = [0, 1, 3, 5, 9];/console.log( myArray.filter(bigEnough) )of course you can inline anonymous instead of declaring bigEnough function.