// Chinese query segmentation: word-level via Intl.Segmenter (with adjacent // single-character run merging for uncommon enterprise names) and term-level // via overlapping two-character windows. let wordSegmenter: Intl.Segmenter | undefined; // The same query string is segmented once per corp × field without memoization; // cache by raw input (bounded like the pinyin cache). const wordsCache = new Map(); const termsCache = new Map(); const SEGMENT_CACHE_LIMIT = 64; function cached(key: string, cache: Map, compute: () => string[]): string[] { const hit = cache.get(key); if (hit !== undefined) return hit; const value = compute(); if (cache.size >= SEGMENT_CACHE_LIMIT) cache.clear(); cache.set(key, value); return value; } export function searchTerms(value: string): string[] { return cached(value, termsCache, () => { const normalized = value.normalize("NFKC").trim().toLowerCase(); const chunks = normalized.match(/[\u4e00-\u9fa5]+|[a-z0-9]+/g) ?? []; return chunks.flatMap((chunk) => { if (!/[\u4e00-\u9fa5]/.test(chunk)) return [chunk]; if (chunk.length <= 2) return [chunk]; const terms: string[] = []; for (let index = 0; index < chunk.length - 1; index += 1) { terms.push(chunk.slice(index, index + 2)); } return terms; }); }); } export function searchWords(value: string): string[] { return cached(value, wordsCache, () => { wordSegmenter ??= new Intl.Segmenter("zh", { granularity: "word" }); const words: string[] = []; let nameChars = ""; const flushName = () => { if (nameChars) words.push(nameChars); nameChars = ""; }; for (const part of wordSegmenter.segment(value.normalize("NFKC").trim().toLowerCase())) { // Uncommon enterprise names are often segmented into individual characters. if (part.isWordLike && /^[\u4e00-\u9fa5]$/.test(part.segment)) { nameChars += part.segment; } else { flushName(); if (part.isWordLike) words.push(part.segment); } } flushName(); return words; }); }