Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Matching multiple ordered candidates #8

Open
jamiebuilds-signal opened this issue Mar 30, 2023 · 0 comments
Open

Matching multiple ordered candidates #8

jamiebuilds-signal opened this issue Mar 30, 2023 · 0 comments

Comments

@jamiebuilds-signal
Copy link

jamiebuilds-signal commented Mar 30, 2023

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"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant