Skip to content

Instantly share code, notes, and snippets.

@theredhead
Created September 18, 2019 13:33
Show Gist options
  • Save theredhead/9d17d28df56c03c1f2c5b9ffb18bd616 to your computer and use it in GitHub Desktop.
Save theredhead/9d17d28df56c03c1f2c5b9ffb18bd616 to your computer and use it in GitHub Desktop.
useful text functions
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