import { escapeRegExp } from "./escapeRegExp";
export function filterMatches(
matches: { match: string; index: number; element: string }[]
): { match: string; index: number; element: string }[] {
const filtered: { match: string; index: number; element: string }[] = [];
for (const current of matches) {
const isContained = filtered.some(
(existing) => current.index >= existing.index && current.index < existing.index + existing.match.length
);
if (!isContained) {
filtered.push(current);
}
}
return filtered;
}
export function getAllMatches(sortedAbbreviations: string[], input: string) {
const allMatches: { match: string; index: number; element: string }[] = [];
sortedAbbreviations.forEach((element) => {
const escapedElement = escapeRegExp(element);
const regex = new RegExp(`(?<=\\s|^|["(])(${escapedElement})(?=\\s|$|[,.!?:;")])`, "g");
let match: RegExpExecArray | null;
while ((match = regex.exec(input)) !== null) {
allMatches.push({ match: match[0], index: match.index, element });
}
});
return allMatches;
}
export function highlightMatches(input: string, matches: { match: string; index: number; element: string }[]): string {
const filteredMatches = filterMatches(matches);
filteredMatches.sort((a, b) => a.index - b.index);
let highlightedString = input;
let offset = 0;
for (const match of filteredMatches) {
const startIndex = match.index + offset;
const endIndex = startIndex + match.match.length;
highlightedString =
highlightedString.slice(0, startIndex) +
`${match.element}` +
highlightedString.slice(endIndex);
offset += `${match.element}`.length - match.match.length;
}
return highlightedString;
}