Last active
June 19, 2019 09:06
-
-
Save Aidurber/9d460ca0afafce8ecbb4b55d0c72fead to your computer and use it in GitHub Desktop.
Type safe text search of collection
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
/** | |
* Perform text search on collection of object for multiple keys | |
* | |
* @export | |
* @template T | |
* @param {T[]} values - The collection | |
* @param {Array<keyof T>} keys - An array of properties on the object (array of strings) | |
* @param {string} term - Search term | |
* @returns | |
*/ | |
export function filterByTerm<T>( | |
values: T[], | |
keys: Array<keyof T>, | |
term: string | |
) { | |
const loweredTerm = term.toLocaleLowerCase(); | |
return (values || []).filter(value => | |
keys.some( | |
key => | |
value[key] && | |
value[key] | |
.toString() | |
.toLocaleLowerCase() | |
.includes(loweredTerm) | |
) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment