As an exercise in higher order functions, I am attempting to code the entire underscore JS library from scratch. I am stuck on the following
var find = function(array, predicate) {
return reduce(array, function (previous,current) {
if (previous !== undefined) {
return previous;
}
else if (predicate(current) === true)
{return current};
}, undefined)
}
My forEach and reduce functions:
var forEach = function(collection, callback) {
if (Array.isArray(collection)) {
for (var i = 0; i < collection.length; i++)
callback(collection[i], i, collection);
}
else {
for (var i in collection) {
callback(collection[i], i, collection);
}
}
};
var reduce = function(collection, callback, startValue) {
forEach(collection, function (element) {
if (startValue !== undefined) {
startValue = callback(startValue, element);
}
else {
startValue = element;
}
});
return startValue;
}
I used the following predicate function to test:
var isOdd = function(x) {
if (x%2 === 1) {
return true
}
else {
return false;
}
};
you'll see that the function find returns the first value in an array rather than the first odd number in the array.
what's most interesting is that when I write the function with the original arr.reduce function like so:
var finder = function(arr, test){
return arr.reduce(function(memo, curr){
if (memo === undefined){
if (test(curr)){return curr;}
}
return memo;
},undefined);
};
any ideas?