Last active
November 23, 2020 19:47
-
-
Save cameronpresley/b9b9b540a67d459e99b19796992c998f to your computer and use it in GitHub Desktop.
Lodash Example of Building a Generic Filter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const _ = require("lodash"); | |
const items = [ | |
{id:1, name: "fluffy", animal: "cat"}, | |
{id: 2, name: "spot", animal: "dog"}, | |
{id: 3, name: "clifford", animal: "dog"}, | |
{id: 4, name: "tony", animal: "tiger"} | |
]; | |
const isAnimal = (animal, item) => item.animal === animal; | |
const hasName = (name, item) => item.name === name | |
// Curry allows us to have a function where we can specify the arguments separately before invoking the functions | |
const curriedIsAnimal = _.curry(isAnimal); | |
const curriedHasName = _.curry(hasName); | |
// Pretend this logic got the text from your user | |
const animalSelection = "dog"; | |
const nameSelection = "clifford"; | |
// Let's define our filters! The more searchboxes we can filter on, this list would be updated | |
const variousFilters = [ | |
curriedIsAnimal(animalSelection), // note that by specifying the first argument here, this function now has a signature of (item=>bool) | |
curriedHasName(nameSelection), // same for this one! | |
]; | |
// Once we have all of these filters defined, we can compose them with the && operator | |
const finalFilter = variousFilters.reduce((a,b) => a&&b, true); | |
const itemsThatMatch = items.filter(finalFilter); | |
console.log(itemsThatMatch); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment