42 lines
1.4 KiB
TypeScript
42 lines
1.4 KiB
TypeScript
import { pinyin } from "pinyin-pro";
|
||
|
||
// Query and target strings repeat across corps and fields within one search run
|
||
// (one query × N corps × 13 fields), so memoize by raw input. Bounded: queries
|
||
// per process are few, but clear instead of growing without limit.
|
||
const fuzzyPinyinCache = new Map<string, string>();
|
||
const PINYIN_CACHE_LIMIT = 128;
|
||
|
||
/**
|
||
* Normalizes Chinese text to toneless pinyin with fuzzy sound rules:
|
||
* - Retroflex vs flat consonants: zh -> z, ch -> c, sh -> s
|
||
* - Front vs back nasal sounds: ang -> an, eng -> en, ing -> in, iang -> ian, uang -> uan
|
||
* - Strips non-alphanumeric whitespace
|
||
*/
|
||
export function normalizeFuzzyPinyin(str: string): string {
|
||
const cached = fuzzyPinyinCache.get(str);
|
||
if (cached !== undefined) return cached;
|
||
|
||
let normalized = "";
|
||
if (str) {
|
||
const pyTokens = pinyin(str, { toneType: "none", type: "array" });
|
||
normalized = pyTokens
|
||
.map((token) =>
|
||
token
|
||
.toLowerCase()
|
||
.replace(/zh/g, "z")
|
||
.replace(/ch/g, "c")
|
||
.replace(/sh/g, "s")
|
||
.replace(/iang/g, "ian")
|
||
.replace(/uang/g, "uan")
|
||
.replace(/ang/g, "an")
|
||
.replace(/eng/g, "en")
|
||
.replace(/ing/g, "in")
|
||
)
|
||
.join("");
|
||
}
|
||
|
||
if (fuzzyPinyinCache.size >= PINYIN_CACHE_LIMIT) fuzzyPinyinCache.clear();
|
||
fuzzyPinyinCache.set(str, normalized);
|
||
return normalized;
|
||
}
|