Building a 60-Line Two-Pass Fuzzy Typo Normalizer in Vanilla JS for 25-Second Browser Trivia
If you give trivia players two minutes to type an answer, most of them will fix their own spelling before pressing Enter. Give them 25 seconds on a phone keyboard, and accurate players routinely lose rounds to missed accent marks, extra leading articles, plural endings, or a single fat-fingered letter.
We ran straight into that UX failure mode while tuning our Krillion Unlimited practice mode on MiniGameDaily. Instead of rewarding obvious answers, rarity-scoring trivia rewards obscure valid picks—precisely the longer, less frequently typed words that mobile autocorrect mangles worst when a countdown clock is ticking down the final five seconds.
Pulling in a full fuzzy-search library would bloat a zero-framework bundle and invite awkward false positives on short three-letter or four-letter answers. So we kept the matcher under 60 lines of dependency-free ES modules and extracted it into a standalone helper repository, sunrain113/rarity-trivia-scorer-js.
(Disclosure: MiniGameDaily is an independent browser-game hub and practice trainer; we are not affiliated with krillion.io.)
Why Strict === Fails Under a 25-Second Mobile Timer
In fast browser puzzle rounds, four harmless player variations show up constantly in valid answers:
- Diacritics and typography: typing
cafe,naive, orcuracaoinstead ofcafé,naïve, orcuraçao, or mixing smart apostrophes (’) with ASCII quotes ('). - Leading English articles: submitting
The Amazonoran octopuswhen the canonical bank storesAmazonoroctopus. - Plural drift: typing
berriesvs.berry, orvolcanoes/dolphinsvs. singular nouns, while true-ss/-us/-isendings likemars,cactus,iris, orglassmust stay untouched. - One-character typos on longer words: typing
chamelion,rhinocros, orkilimanjarowith one swapped or dropped letter under time pressure.
Meanwhile, blind fuzzy matching has an equally painful failure mode: allowing edit distance 1 everywhere turns bat into cat, mars into cars, or ant into art. Under a competitive rarity curve, letting accidental guesses sneak through destroys trust in the leaderboard.
That is why we split matching into two explicit passes: deterministic canonical normalization first, length-guarded Levenshtein lookup second.
Pass 1: Deterministic Normalization (normalizeAnswer)
Here is the exact normalization helper from our open-source sunrain113/rarity-trivia-scorer-js module:
export function normalizeAnswer(input) { if (typeof input !== 'string') return ''; let clean = input .normalize('NFD') .replace(/[\u0300-\u036f]/g, '') .toLowerCase() .replace(/['’`]/g, '') .replace(/[^a-z0-9\s]/g, ' ') .replace(/\s+/g, ' ') .trim() .replace(/^(?:the|an|a)\s+/i, ''); if (clean.length > 4 && clean.endsWith('ies')) { clean = clean.slice(0, -3) + 'y'; } else if ( clean.length > 3 && clean.endsWith('s') && !clean.endsWith('ss') && !clean.endsWith('us') && !clean.endsWith('is') ) { clean = clean.slice(0, -1); } return clean; } Three design details matter in practice:
- Unicode NFD decomposition before punctuation stripping: Calling
.normalize('NFD')separates base characters from combining marks (\u0300-\u036f), convertingSão Paulointosao paulowithout maintaining lookup tables. - Apostrophe removal before symbol cleanup: Stripping
['’]first avoids splitting contractions or possessives into artificial tokens (McDonald'sstaysmcdonalds, notmcdonald s`). - Conservative suffix guards: Stripping
-sunconditionally breaks nouns likemars,iris,glass,bus, orcactus. Checkingclean.length > 3and guarding-ss,-us, and-isprevents mangling singular nouns while folding standard plurals (dolphins->dolphin,berries->berry) cleanly.
Because both user input and canonical bank entries run through normalizeAnswer, exact semantic equivalents collide deterministically in Pass 1 with zero false positives.
Pass 2: Guarded O(n) Levenshtein Fuzzy Lookup (matchAnswer)
Only when Pass 1 misses do we fall back to bounded edit distance:
`js
export function levenshtein(a, b) {
if (a === b) return 0;
if (!a.length) return b.length;
if (!b.length) return a.length;
const prev = Array.from({ length: b.length + 1 }, (_, j) => j);
for (let i = 1; i <= a.length; i++) {
let diag = prev[0];
prev[0] = i;
for (let j = 1; j <= b.length; j++) {
const saved = prev[j];
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
prev[j] = Math.min(prev[j] + 1, prev[j - 1] + 1, diag + cost);
diag = saved;
}
}
return prev[b.length];
}
`
Notice it keeps only a single rolling prev row in memory instead of allocating an m x n matrix—a neat zero-GC pattern for mobile browsers.
The safety net sits around levenshtein inside matchAnswer:
`js
export function matchAnswer(input, entries, options = {}) {
const { maxEditDistance = 1, minFuzzyLength = 5 } = options;
const normalizedInput = normalizeAnswer(input);
if (!normalizedInput || !Array.isArray(entries)) {
return { matched: false, matchType: null, distance: Infinity, normalizedInput, entry: null };
}
const normalizedEntries = entries.map((entry) => ({
entry,
normalized: normalizeAnswer(extractEntryText(entry)),
}));
const exactHit = normalizedEntries.find((item) => item.normalized === normalizedInput);
if (exactHit) {
return { matched: true, matchType: 'exact', distance: 0, normalizedInput, entry: exactHit.entry };
}
if (maxEditDistance <= 0 || normalizedInput.length < minFuzzyLength) {
return { matched: false, matchType: null, distance: Infinity, normalizedInput, entry: null };
}
let bestHit = null;
let bestDistance = Infinity;
for (const item of normalizedEntries) {
if (!item.normalized || item.normalized.length < minFuzzyLength) continue;
if (Math.abs(item.normalized.length - normalizedInput.length) > maxEditDistance) continue;
const dist = levenshtein(normalizedInput, item.normalized);
if (dist <= maxEditDistance && dist < bestDistance) {
bestDistance = dist;
bestHit = item;
}
}
return bestHit
? { matched: true, matchType: 'fuzzy', distance: bestDistance, normalizedInput, entry: bestHit.entry }
: { matched: false, matchType: null, distance: Infinity, normalizedInput, entry: null };
}
`
Two rules keep fuzzy tolerance fair in Krillion endless mode:
- Minimum fuzzy length (
minFuzzyLength = 5): Short 3–4 letter words (mars,lion,gold,oak) never fuzzy-match, blockingcars -> marsorboat -> goat. Only answers with at least five normalized characters qualify (chamelion -> chameleon,platyps -> platypus). - Symmetric length guard (
maxEditDistance = 1): Both the player string and candidate entry must satisfy>= 5characters and differ by at most1character in length before running DP, skipping pointless comparisons in a single integer check.
Calibrating Ocean-Depth Rarity Buckets (RARITY_BANDS)
Matching an answer is half the equation; scoring how common or obscure it is determines whether a round feels strategic. Scoring raw 1 / share directly makes tiny sample fluctuations swing wildly between rounds.
Instead, we map normalized crowd shares into six calibrated ocean-depth tiers via scoreRarityShare:
| Crowd Share | Score | Ocean Depth | Tier Label |
|---|---|---|---|
>= 14% | 10 pts | 100 m | Plankton |
>= 8% | 15 pts | 150 m | Too Clever |
>= 4% | 30 pts | 300 m | Schooler |
>= 2% | 60 pts | 600 m | Rare |
>= 0.8% | 80 pts | 800 m | Deep Cut |
< 0.8% | 100 pts | 1,000 m | One in a Krillion |
Why add the 15 pts (Too Clever) band right above 10 pts (Plankton)? Crowd data in rarity trivia consistently exhibits a second-choice spike: when dozens of players consciously skip the #1 reflex answer, they crowd onto the exact same "clever" #2 fallback (8%–13.9% share). Explicitly buckling that tier into Too Clever pushes players one step deeper rather than letting second-best reflexes score like genuinely rare picks.
Checking Prompt Constraints Across the Bank (summarizeDiveBank)
Our helper module also exports summarizeDiveBank(prompts), which flags parenthetical or negative disqualifiers (no, not, without, only, starting with, over/under, parentheses) alongside per-tier counts. Across a benchmark slice of 112 prompts and 1,977 tiered answers, 35 prompts (31.3%) included explicit exclusion clauses in the prompt wording. When players miss a valid rare word, pairing fast typo normalization with post-round constraint highlighting shows right away whether the issue was spelling or a disqualified clue.
Try the Live Practice Game or Grab the Code
You can inspect the full 60-line module, unit tests (node --test), and MIT license on GitHub at sunrain113/rarity-trivia-scorer-js, or jump straight into a live 25-second round with our Krillion unlimited guide and browse all daily puzzles over on MiniGameDaily.