Skip to content

Matching multiple ordered candidates #8

@jamiebuilds-signal

Description

@jamiebuilds-signal

It is occasionally useful to be able to test if multiple locales are good candidates according a user's preferences. For example:

  • Configuring spellcheckers for multiple languages.
  • Display a locale <select> with the user's preferences hoisted to the top.

I will say it's totally possible to do this with just this API, it's just slightly involved:

let requestedLocales = ["fa-FR", "fr-FR"]
let availableLocales = ["en-US", "fr-FR", "fa-IR", "zh-Hans-CN"]
let defaultLocale = "en-US"
let options = { algorithm: "best fit" }
let fakeDefaultLocale = "en-x-ignore";

let matchedLocales = []

requestedLocales.forEach((requestedLocale) => {
  let match = Intl.LocaleMatcher.match(
    [requestedLocale], 
    availableLocales, 
    fakeDefaultLocale,
    options
  )
  if (match !== fakeDefaultLocale) {
    matchedLocales.push(match)
  }
})

if (matchedLocales.length === 0) {
  matchedLocales.push(defaultLocale)
}

// matchedLocales == ["fa-IR", "fr-FR"]

However, it seems like an easy thing to just bake into this API to make it more useful:

let matchedLocales = Intl.LocaleMatcher.matchMany(
  requestedLocales, 
  availableLocales, 
  defaultLocale,
  options
)
// matchedLocales == ["fa-IR", "fr-FR"]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions