Created
June 6, 2021 21:47
-
-
Save yduman/bea7581f0a331edac2b015462027a0d0 to your computer and use it in GitHub Desktop.
Reusable array search predicates
This file contains hidden or 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
// 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