@@ -205,25 +205,44 @@ export function findMatchingDistance(desired: string, supported: string) {
205205 return matchingDistance
206206}
207207
208+ interface LocaleMatchingResult {
209+ distances : Record < string , Record < string , number > >
210+ matchedSupportedLocale ?: string
211+ matchedDesiredLocale ?: string
212+ }
213+
208214export function findBestMatch (
209- desired : string ,
215+ requestedLocales : readonly string [ ] ,
210216 supportedLocales : readonly string [ ] ,
211217 threshold = DEFAULT_MATCHING_THRESHOLD
212- ) : string | undefined {
213- let bestMatch = undefined
218+ ) : LocaleMatchingResult {
214219 let lowestDistance = Infinity
215- supportedLocales . forEach ( ( supported , i ) => {
216- // Add some weight to the distance based on the order of the supported locales
217- const distance = findMatchingDistance ( desired , supported ) + i
218- if ( distance < lowestDistance ) {
219- lowestDistance = distance
220- bestMatch = supported
220+ let result : LocaleMatchingResult = {
221+ matchedDesiredLocale : '' ,
222+ distances : { } ,
223+ }
224+ requestedLocales . forEach ( ( desired , i ) => {
225+ if ( ! result . distances [ desired ] ) {
226+ result . distances [ desired ] = { }
221227 }
228+ supportedLocales . forEach ( ( supported , j ) => {
229+ // Add some weight to the distance based on the order of the supported locales
230+ // Add penalty for the order of the requested locales
231+ const distance = findMatchingDistance ( desired , supported ) + j + i * 40
232+
233+ result . distances [ desired ] [ supported ] = distance
234+ if ( distance < lowestDistance ) {
235+ lowestDistance = distance
236+ result . matchedDesiredLocale = desired
237+ result . matchedSupportedLocale = supported
238+ }
239+ } )
222240 } )
223241
224242 if ( lowestDistance >= threshold ) {
225- return
243+ result . matchedDesiredLocale = undefined
244+ result . matchedSupportedLocale = undefined
226245 }
227246
228- return bestMatch
247+ return result
229248}
0 commit comments