|
| 1 | +import normalizeString from './normalizeString' |
| 2 | + |
| 3 | +const mapReplacedString = ( |
| 4 | + text: string, |
| 5 | + map: [string, string][], |
| 6 | +): { sanitizedText: string; replacementMap: number[] } => { |
| 7 | + let transformed = '' |
| 8 | + const repMap: number[] = [] |
| 9 | + let i = 0 |
| 10 | + let matcher |
| 11 | + while (i < text.length) { |
| 12 | + const findMatch = (index: number) => (element: [string, string]) => text.startsWith(element[0], index) |
| 13 | + |
| 14 | + matcher = map.find(findMatch(i)) |
| 15 | + if (matcher) { |
| 16 | + transformed += matcher[1] |
| 17 | + repMap.push(...Array(matcher[1].length).fill(i)) |
| 18 | + i += matcher[0].length |
| 19 | + } else { |
| 20 | + transformed += text[i] |
| 21 | + repMap.push(i) |
| 22 | + i += 1 |
| 23 | + } |
| 24 | + } |
| 25 | + return { |
| 26 | + sanitizedText: transformed, |
| 27 | + replacementMap: repMap, |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +export const findMatchingSections = ({ |
| 32 | + searchWords, |
| 33 | + textToHighlight, |
| 34 | +}: { |
| 35 | + searchWords: (string | RegExp)[] |
| 36 | + textToHighlight: string |
| 37 | +}): { start: number; end: number }[] => { |
| 38 | + const { sanitizedText, replacementMap } = mapReplacedString(normalizeString(textToHighlight), [['ß', 'ss']]) |
| 39 | + |
| 40 | + let result: { start: number; end: number }[] = [] |
| 41 | + if (replacementMap.length > 0) { |
| 42 | + searchWords.forEach((word: string | RegExp) => { |
| 43 | + let matches: { start: number; end: number }[] = [] |
| 44 | + if (typeof word === 'string' && word !== '') { |
| 45 | + const sanitizedWord = normalizeString(word).replace('ß', 'ss') |
| 46 | + const regex = new RegExp(sanitizedWord, 'gi') |
| 47 | + |
| 48 | + matches = [...sanitizedText.matchAll(regex)].map(match => { |
| 49 | + const start = replacementMap[match.index] |
| 50 | + const end = replacementMap[match.index + match[0].length] ?? textToHighlight.length |
| 51 | + if (start !== undefined && !Number.isNaN(start) && !Number.isNaN(end)) { |
| 52 | + return { |
| 53 | + start, |
| 54 | + end, |
| 55 | + } |
| 56 | + } |
| 57 | + return { start: 0, end: 0 } |
| 58 | + }) |
| 59 | + } |
| 60 | + |
| 61 | + if (matches.length > 0) { |
| 62 | + result = result.concat(matches) |
| 63 | + } |
| 64 | + }) |
| 65 | + } |
| 66 | + |
| 67 | + return result |
| 68 | +} |
| 69 | + |
| 70 | +export default findMatchingSections |
0 commit comments