Created
September 18, 2019 13:33
-
-
Save theredhead/9d17d28df56c03c1f2c5b9ffb18bd616 to your computer and use it in GitHub Desktop.
useful text functions
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
export function object_to_searchable_text(obj: any): string { | |
if (obj === undefined) { | |
return ''; | |
} else if (typeof obj === 'object') { | |
const parts = []; | |
for (const property of Object.keys(obj)) { | |
parts.push(object_to_searchable_text(obj[property])); | |
} | |
return parts.join(' '); | |
} else if (Array.isArray(obj)) { | |
return obj.join(' '); | |
} else { | |
return obj.toString(); | |
} | |
} | |
export function text_contains_all(text: string, searchText: string): boolean { | |
if (searchText.length === 0) { | |
return true; | |
} | |
const haystack = text.toLowerCase(); | |
const texts = searchText | |
.split(/\s/) | |
.map(x => x.toLowerCase().trim()) | |
.filter(x => x !== ''); | |
for (const needle of texts) { | |
if (haystack.indexOf(needle) === -1) { | |
return false; | |
} | |
} | |
return true; | |
} | |
export function object_matches_searchtext( | |
obj: any, | |
searchText: string | |
): boolean { | |
try { | |
const text = object_to_searchable_text(obj).toLowerCase(); | |
return text_contains_all(text, searchText); | |
} catch (e) { | |
console.error('object_matches_searchtext', e); | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment