Skip to content

Instantly share code, notes, and snippets.

@cameronpresley
Last active November 23, 2020 19:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cameronpresley/b9b9b540a67d459e99b19796992c998f to your computer and use it in GitHub Desktop.
Save cameronpresley/b9b9b540a67d459e99b19796992c998f to your computer and use it in GitHub Desktop.
Lodash Example of Building a Generic Filter
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