While working on a functional programming challenge I came across online, the task was to create a custom 'filter' method in JavaScript. This method should take two arguments - a collection and a test function that returns either 'true' or 'false. It should then iterate over the collection using an 'each' function previously implemented and return the resulting array.
I've successfully completed the initial part of the exercise by developing a function that mimics JS's forEach method:
var each = function(collection, iterator) {
if(Array.isArray(collection)){
for(var i = 0; i < collection.length; i++){
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!");
}
};
To test my function, I used the following example:
function returnOdds(currentEl) {
return currentEl % 2 !== 0;
}
console.log(filter([1, 2, 3], returnOdds)); // output: 1, 3
Now, I am unsure how to incorporate my 'each' function within the 'filter' function. I'm questioning whether it is legal to call 'each' on the 'collection' parameter inside filter.
Alternatively, can I use the 'test' parameter as a function to check if each element in the collection is odd or even?
function filter(collection, test) {
var odd = function(each()){
each(collection){
if(collection[i] !== 0){
return odd;
}
}
}
}
I am uncertain if any of these approaches are correct or feasible.