TelegramPWA/src/util/searchWords.ts

43 lines
1.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

let RE_NOT_LETTER: RegExp;
try {
RE_NOT_LETTER = new RegExp('[^\\p{L}\\p{M}]+', 'ui');
} catch (e) {
// Support for older versions of firefox
RE_NOT_LETTER = new RegExp('[^\\wа-яё]+', 'i');
}
export default function searchWords(haystack: string, needle: string | string[]) {
if (!haystack || !needle) {
return false;
}
const needleWords = typeof needle === 'string' ? needle.toLowerCase().split(RE_NOT_LETTER) : needle;
const haystackLower = haystack.toLowerCase();
// @optimization
if (needleWords.length === 1 && !haystackLower.includes(needleWords[0])) {
return false;
}
let haystackWords: string[];
return needleWords.every((needleWord) => {
if (!haystackLower.includes(needleWord)) {
return false;
}
if (!haystackWords) {
haystackWords = haystackLower.split(RE_NOT_LETTER);
}
return haystackWords.some((haystackWord) => haystackWord.startsWith(needleWord));
});
}
export function prepareSearchWordsForNeedle(needle: string) {
const needleWords = needle.toLowerCase().split(RE_NOT_LETTER);
return (haystack: string) => searchWords(haystack, needleWords);
}