My main goal for academic purposes is to solve this problem and for the most part I did. Also I wanted to make sure that I was not missing a fundamental part of reduce by not understanding what is wrong with my code.
This is how I would solve it, I've attached my reduce function as well as filter function. I believe my reduce function works however, my filter function isn't quite working so well as I can't pass my test cases.
1) Why am i not hitting the last element of the array?
I've noticed that prev and curr actually never return 5 at any point of the reduce function. Am I missing something in my reduce function?
myArray = [1,2,3,4,5];
function each(collection, action){
if(Array.isArray(collection)){
for(var i = 0; i < collection.length; i ++){
action(collection[i]);
}
}
else if(typeof(collection) === "object"){
for (var property in collection){
action(collection[property]);
}
}
}
function reduce(collection, combine, start){
each(collection, function(element){
if(start === undefined){
return start = element;
}
else {
return start = combine(start, element);
}
});
return start;
}
function filterR(collection, predicate){
var aR = [];
reduce(collection, function(prev, curr){
if(predicate(prev)){
aR.push(prev);
}
if(predicate(curr)){
aR.push(curr);
}
});
return aR;
}
console.log(filter(myArray, function(val){return val % 5 === 0;})); //expected [5]
console.log(filter(myArray, function(val){return val <= 5;})); //expected [1,2,3,4,5]
eachfunction