( requestedLocales: readonly string[], supportedLocales: readonly string[], threshold: number = DEFAULT_MATCHING_THRESHOLD )
| 339 | const canonicalizedSupportedCache = new WeakMap<readonly string[], string[]>() |
| 340 | |
| 341 | export function findBestMatch( |
| 342 | requestedLocales: readonly string[], |
| 343 | supportedLocales: readonly string[], |
| 344 | threshold: number = DEFAULT_MATCHING_THRESHOLD |
| 345 | ): LocaleMatchingResult { |
| 346 | let lowestDistance = Infinity |
| 347 | let result: LocaleMatchingResult = { |
| 348 | matchedDesiredLocale: '', |
| 349 | distances: {}, |
| 350 | } |
| 351 | |
| 352 | // Get or compute canonicalized supported locales (one by one to preserve indices) |
| 353 | let canonicalizedSupportedLocales = |
| 354 | canonicalizedSupportedCache.get(supportedLocales) |
| 355 | if (!canonicalizedSupportedLocales) { |
| 356 | canonicalizedSupportedLocales = supportedLocales.map(locale => { |
| 357 | try { |
| 358 | const canonical = Intl.getCanonicalLocales([locale]) |
| 359 | return canonical[0] || locale |
| 360 | } catch { |
| 361 | return locale |
| 362 | } |
| 363 | }) |
| 364 | canonicalizedSupportedCache.set( |
| 365 | supportedLocales, |
| 366 | canonicalizedSupportedLocales |
| 367 | ) |
| 368 | } |
| 369 | |
| 370 | const supportedSet = new Set(canonicalizedSupportedLocales) |
| 371 | |
| 372 | // === TIER 1: FAST PATH - Exact Match === |
| 373 | // Check for exact matches in ALL requested locales |
| 374 | // This is the fastest path and handles the majority of real-world cases |
| 375 | for (let i = 0; i < requestedLocales.length; i++) { |
| 376 | const desired = requestedLocales[i] |
| 377 | if (supportedSet.has(desired)) { |
| 378 | const distance = 0 + i * 40 |
| 379 | result.distances[desired] = {[desired]: distance} |
| 380 | |
| 381 | if (distance < lowestDistance) { |
| 382 | lowestDistance = distance |
| 383 | result.matchedDesiredLocale = desired |
| 384 | result.matchedSupportedLocale = desired |
| 385 | } |
| 386 | |
| 387 | // Only return immediately if this is the first requested locale (distance=0) |
| 388 | // Otherwise, continue checking for potentially better matches |
| 389 | if (i === 0) { |
| 390 | return result |
| 391 | } |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | // If we found an exact match in Tier 1 (but not for first locale), check Tier 2 |
| 396 | // to see if there's a better fallback match with lower distance |
| 397 | // If no exact match found, Tier 2 will find fallback matches |
| 398 |
no test coverage detected