In a functional programming exercise I found online, the instructions are as follows:
"Implement JavaScript’s native ‘filter’ method that takes two arguments (a collection and a test function that returns either a ‘true’ or a ‘false’) and iterates over the collection using the ‘each’ function you wrote earlier and returns the resultant array."
I've already completed the first part of the exercise and created a function that implements JS' forEach method:
var each = function(collection, iterator) {
if(Array.isArray(collection)){
for(var i = 0; i < collection.length; i++){
// value, key/property, collection
iterator(collection[i],i,collection);
}
} else if (typeof collection === "object"){
for(var property in collection){
iterator(collection[property], property, collection);
}
}else{
console.log("you messed up!");
}
};
Test my function with:
function returnOdds(currentEl) {
return currentEl % 2 !== 0;
}
console.log(filter([1, 2, 3], returnOdds)); // output: 1, 3
I'm not sure how to call my 'each' function on the 'collection' parameter inside my filter function.
Is this legal to do?
function filter(collection, test) {
each(collection);
}
Or perhaps I can call the 'test' parameter as a function that checks to see if collection[i] is not an even/odd number?
function filter(collection, test) {
var odd = function(each()){
each(collection){
if(collection[i] !== 0){
return odd;
}
}
}
}
I am wondering if any of this even makes sense or can be done.