Skip to content

Instantly share code, notes, and snippets.

@yduman
Created June 6, 2021 21: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 yduman/bea7581f0a331edac2b015462027a0d0 to your computer and use it in GitHub Desktop.
Save yduman/bea7581f0a331edac2b015462027a0d0 to your computer and use it in GitHub Desktop.
Reusable array search predicates
// CREDIT TO: https://jasonformat.com/reusable-array-search-predicates/
// Given an Array of objects:
const blogPosts = [
{ name:'one', tags:['a', 'b'], published: '2016-10-31' },
{ name:'two', tags:['c'], published: '2019-01-05' },
{ name:'three', tags:['b'], published: '2021-06-06' },
...
];
// Create reusable search predicates using `this`:
function $hasName(item) { return item.name === this }
function $hasTag(item) { return item.tags.includes(this) }
function $publishedAfter(item) { return new Date(item.published) > this }
// ...and specify the comparison value dynamically:
blogPosts.find($hasName, 'one'); // {name:'one'…}
blogPosts.findIndex($hasName, 'two'); // 1
blogPosts.every($hasTag, 'b'); // true
blogPosts.filter($hasTag, 'b'); // [{name:'one'…}, {name:'three'…}]
blogPosts.filter($publishedAfter, new Date(2020, 12, 25)); // [{name:'three'…}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment