We're a place where coders share, stay up-to-date and grow their careers.
i also suggest a re write to this functionality of the last pass
filterMaleFrogs = function (frog) { return frog.gender === 'Male' }; filterAdultFrogs = function (frog) { return frog.age >= 10 }; filterFrogNamesThatStartWithHippo = function (frog) { return frog.name.toLowerCase().startsWith('hippo') }; filterGmailEmails = function (frog) { return /gmail.com/i.test(frog.email) }; function composeFrogFilterersModified(...fns) { return function (frogs) { return frogs.filter( combineFilters(fns) ); } } function combineFilters(fns) { return function (frog) { return fns.reduce(function (accumulatedFilter, currentFilter) { if(accumulatedFilter === false) { return false; } return !!currentFilter(frog); }, true); } } const applyFrogFilterersComposedAgain = composeFrogFilterersModified( filterMaleFrogs, filterAdultFrogs, filterFrogNamesThatStartWithHippo, filterGmailEmails, ); const allFilteredFrogsModified = applyFrogFilterersComposedAgain(combinedFrogsList); console.log('all filtered frogs: ', allFilteredFrogsModified);
from my understanding, this will only go once per frog and not create array.filter 4 times please correct me if iam wrong or missed something on your implementation
I love the use of reduce with collections of functions! +1 @serjoa 🦄
reduce
Hi SerjoA, thank you for the suggestion and the workaround!
I will edit the post and swap out the current code example with the example you provided because its correct.
I'm going to make a slight modification to your combineFilters function to run this instead:
combineFilters
function combineFilters(...fns) { return function (frog) { for (let i = 0; i < fns.length; i++) { const filter = fns[i] const passes = filter(frog) if (passes) { continue } else { return false } } return true } }
This is a slightly more optimized version which reduces the amount of iterations as much as possible.
Thank you!
great, looks good
i also suggest a re write to this functionality of the last pass
from my understanding, this will only go once per frog and not create array.filter 4 times
please correct me if iam wrong or missed something on your implementation
I love the use of
reduce
with collections of functions!+1 @serjoa 🦄
Hi SerjoA, thank you for the suggestion and the workaround!
I will edit the post and swap out the current code example with the example you provided because its correct.
I'm going to make a slight modification to your
combineFilters
function to run this instead:This is a slightly more optimized version which reduces the amount of iterations as much as possible.
Thank you!
great, looks good