| 1 |
/** |
| 2 |
* @typedef {{ |
| 3 |
* match: string; |
| 4 |
* start: number; |
| 5 |
* end: number; |
| 6 |
* }} NormalizedMatchResult |
| 7 |
*/ |
| 8 |
|
| 9 |
/** |
| 10 |
* Normalizes a string for use in comparison. |
| 11 |
* |
| 12 |
* @example |
| 13 |
* normalize("déçûmes") === normalize("DECUMES") |
| 14 |
* normalize("𝔖𝔥𝔯𝔢𝔨") === normalize("Shrek") |
| 15 |
* normalize("Scleßin") === normalize("Sclessin") |
| 16 |
* normalize("Œdipe") === normalize("OeDiPe") |
| 17 |
* |
| 18 |
* @param {string} str |
| 19 |
* @returns {string} |
| 20 |
*/ |
| 21 |
export function normalize(str) { |
| 22 |
return casefold(unaccent(expandLigatures(str.normalize("NFKC")))); |
| 23 |
} |
| 24 |
|
| 25 |
/** |
| 26 |
* Searches for "substr" in "src". The search is performed on normalized strings |
| 27 |
* so that "ce" can match "Cédric". |
| 28 |
* |
| 29 |
* @param {string} src |
| 30 |
* @param {string} substr |
| 31 |
* @returns {NormalizedMatchResult} |
| 32 |
*/ |
| 33 |
export function normalizedMatch(src, substr) { |
| 34 |
if (!substr) { |
| 35 |
return { start: 0, end: 0, match: "" }; |
| 36 |
} |
| 37 |
/** |
| 38 |
* Array.from splits the string into an array of codepoints. This avoids |
| 39 |
* processing unpaired surrogates, which could lead to unexpected results. |
| 40 |
* |
| 41 |
* "𝔖"[0]; // "\ud835" ← unpaired surrogate!! |
| 42 |
* Array.from("𝔖")[0]; // "𝔖" |
| 43 |
* |
| 44 |
* "𝔖".split(""); // Array [ "\ud835", "\udd16" ] |
| 45 |
* Array.from("𝔖"); // Array [ "𝔖" ] |
| 46 |
* |
| 47 |
* "𝔖".split("").map((c) => c.normalize("NFKC")).join(""); // "𝔖" |
| 48 |
* Array.from("𝔖").map((c) => c.normalize("NFKC")).join(""); // "S" |
| 49 |
*/ |
| 50 |
const srcAsCodepoints = Array.from(src); |
| 51 |
/** |
| 52 |
* Instead of calling normalize directly on the source string, the source is |
| 53 |
* split into an array of codepoints, where each of the elements is |
| 54 |
* normalized individually. This is because this function is expected to |
| 55 |
* return the start and end indexes of the match in the *original*, |
| 56 |
* unnormalized string, but strings can grow in length during normalization, |
| 57 |
* which would alter the indexes. Now, even if the length of the individual |
| 58 |
* elements grows, the length of the containing array remains the same. |
| 59 |
*/ |
| 60 |
const normalizedSrc = srcAsCodepoints.map(normalize); |
| 61 |
const normalizedSubstr = Array.from(normalize(substr)); |
| 62 |
/** |
| 63 |
* normalizedSrc can contain empty strings if the source is an NFD string, |
| 64 |
* corresponding to diacritics that have been stripped off. They must be |
| 65 |
* taken into account in the length calculation to get the indexes right, |
| 66 |
* hence Math.max(x.length, 1). |
| 67 |
*/ |
| 68 |
const flattenSrcLength = normalizedSrc.reduce((acc, x) => acc + Math.max(x.length, 1), 0); |
| 69 |
for (let i = 0; i <= flattenSrcLength - normalizedSubstr.length; ++i) { |
| 70 |
const substrStack = Array.from(normalizedSubstr).reverse(); |
| 71 |
for (let j = 0; i + j < normalizedSrc.length; ++j) { |
| 72 |
const current = normalizedSrc[i + j]; |
| 73 |
// "every" in case normalization expanded current to several chars |
| 74 |
if (![...current].every((c) => substrStack.length === 0 || c === substrStack.pop())) { |
| 75 |
break; |
| 76 |
} |
| 77 |
if (substrStack.length === 0) { |
| 78 |
// full substring matched, return the result 😤 |
| 79 |
const start = srcAsCodepoints.slice(0, i).join("").length; |
| 80 |
const match = srcAsCodepoints.slice(i, i + j + 1).join(""); |
| 81 |
const end = start + match.length; |
| 82 |
return { start, end, match }; |
| 83 |
} |
| 84 |
} |
| 85 |
} |
| 86 |
return { start: -1, end: -1, match: "" }; |
| 87 |
} |
| 88 |
|
| 89 |
/** |
| 90 |
* Searches for "substr" in "src" as is done in normalizedMatch |
| 91 |
* but returns an array of all successful matches |
| 92 |
* |
| 93 |
* @param {string} src |
| 94 |
* @param {string} substr |
| 95 |
* @returns {NormalizedMatchResult[]} |
| 96 |
*/ |
| 97 |
export function normalizedMatches(src, substr) { |
| 98 |
const matches = []; |
| 99 |
let index = 0; |
| 100 |
while (src.length) { |
| 101 |
const { start, end, match } = normalizedMatch(src, substr); |
| 102 |
if (match) { |
| 103 |
matches.push({ start: index + start, end: index + end, match }); |
| 104 |
index += end; |
| 105 |
src = src.slice(end); |
| 106 |
} else { |
| 107 |
break; |
| 108 |
} |
| 109 |
} |
| 110 |
return matches; |
| 111 |
} |
| 112 |
|
| 113 |
const DECOMPOSITION_BY_LIGATURE = new Map([ |
| 114 |
["Æ", "Ae"], // Danish, Norwegian, Icelandic, French (rare)... |
| 115 |
["æ", "ae"], |
| 116 |
["Œ", "Oe"], // French: "Richard Cœur de Lion" |
| 117 |
["œ", "oe"], |
| 118 |
["IJ", "IJ"], // Dutch: "IJzer" |
| 119 |
["ij", "ij"], |
| 120 |
]); |
| 121 |
|
| 122 |
/** |
| 123 |
* Splits ligatures into their constituent glyphs, e.g. turns Œ into Oe. |
| 124 |
* |
| 125 |
* @param {string} str |
| 126 |
* @returns {string} |
| 127 |
*/ |
| 128 |
function expandLigatures(str) { |
| 129 |
return Array.from(str, (char) => DECOMPOSITION_BY_LIGATURE.get(char) ?? char).join(""); |
| 130 |
} |
| 131 |
|
| 132 |
/** |
| 133 |
* Diacritics are marks, such as accents or cedilla, that when added to a letter |
| 134 |
* change its pronunciation or meaning. Unicode has a category for them, but it |
| 135 |
* doesn't consider characters like "ø" to be a diacritical "o". Below is a list |
| 136 |
* of characters that could be considered "diacritical characters" but aren't |
| 137 |
* labeled as such by Unicode. |
| 138 |
*/ |
| 139 |
const DIACRITIC_LIKES = new Map([ |
| 140 |
["Ø", "O"], // notably used in Danish and Norwegian: "Jørgen" |
| 141 |
["ø", "o"], |
| 142 |
["Ł", "L"], // notably used in Polish: "Paweł" |
| 143 |
["ł", "l"], |
| 144 |
["Ð", "D"], // Icelandic, "Borgarfjörður" |
| 145 |
["ð", "d"], |
| 146 |
["Ħ", "H"], // Maltese, "Ħamrun Spartans Football Club" |
| 147 |
["ħ", "h"], |
| 148 |
["Ŧ", "T"], // apparently used in Sámi languages, very few speakers |
| 149 |
["ŧ", "t"], |
| 150 |
]); |
| 151 |
|
| 152 |
/** |
| 153 |
* Removes "diacritics" (funny marks added to letters, such as accents and |
| 154 |
* cedillas) from a string. |
| 155 |
* |
| 156 |
* @param {string} str |
| 157 |
* @returns {string} |
| 158 |
*/ |
| 159 |
function unaccent(str) { |
| 160 |
return Array.from( |
| 161 |
str.normalize("NFD").replace(/\p{Nonspacing_Mark}/gu, ""), |
| 162 |
(char) => DIACRITIC_LIKES.get(char) ?? char |
| 163 |
).join(""); |
| 164 |
} |
| 165 |
|
| 166 |
/** |
| 167 |
* Normalizes string case for use in comparison. |
| 168 |
* |
| 169 |
* Some characters change length when converted from one case to another. A |
| 170 |
* common example is the German letter "ß," which becomes "SS" when uppercased. |
| 171 |
* This function ensures that these special cases are handled correctly. |
| 172 |
* |
| 173 |
* ⚠ Doesn't preserve "Turkish I"s. |
| 174 |
* |
| 175 |
* @see https://www.w3.org/TR/charmod-norm/#definitionCaseFolding |
| 176 |
* @see https://www.unicode.org/Public/UNIDATA/CaseFolding.txt |
| 177 |
* |
| 178 |
* @example |
| 179 |
* casefold("AAAAAAAA") // "aaaaaaaa" |
| 180 |
* casefold("և") // "ԵՒ" |
| 181 |
* casefold("Kevin Großkreutz") // "kevin grosskreutz" |
| 182 |
* casefold("Diyarbakır") // "diyarbakir" |
| 183 |
* casefold("ß") !== "ß".toLowerCase() // true |
| 184 |
* casefold("ß") === casefold("SS") // true |
| 185 |
* |
| 186 |
* @param {string} str |
| 187 |
* @returns {string} lowercase string after "full case folding" |
| 188 |
*/ |
| 189 |
function casefold(str) { |
| 190 |
return str.toLowerCase().toUpperCase().toLowerCase(); |
| 191 |
} |