MCPcopy
hub / github.com/formatjs/formatjs / CanonicalizeLocaleList

Function CanonicalizeLocaleList

packages/intl-getcanonicallocales/index.ts:29–90  ·  view source on GitHub ↗

* https://tc39.es/ecma402/#sec-canonicalizelocalelist * @param locales

(
  locales?:
    | string[]
    | string
    | Intl.Locale
    | Intl.Locale[]
    | ArrayLike<string | Intl.Locale>
)

Source from the content-addressed store, hash-verified

27 * @param locales
28 */
29function CanonicalizeLocaleList(
30 locales?:
31 | string[]
32 | string
33 | Intl.Locale
34 | Intl.Locale[]
35 | ArrayLike<string | Intl.Locale>
36): string[] {
37 // Step 1-2: If locales is undefined, return empty list
38 if (locales === undefined) {
39 return []
40 }
41
42 const seen: string[] = []
43
44 // Step 3-4: Handle string or Locale object by wrapping in array
45 // Per spec: "If Type(locales) is String or Type(locales) is Object and locales has an
46 // [[InitializedLocale]] internal slot, then Let O be CreateArrayFromList(« locales »)"
47 if (typeof locales === 'string' || isLocaleObject(locales)) {
48 locales = [locales as string | Intl.Locale]
49 }
50
51 // Step 5-6: Convert to object and get length for array-like objects
52 // Per spec: "Let O be ? ToObject(locales)" and "Let len be ? ToLength(? Get(O, "length"))"
53 const O = Object(locales)
54 const len = typeof O.length === 'number' ? O.length : 0
55
56 // Step 7: Iterate through elements
57 for (let k = 0; k < len; k++) {
58 // Check if property exists
59 if (!(k in O)) {
60 continue
61 }
62
63 const kValue = O[k]
64
65 // Step 7c-d: Extract locale string
66 let tag: string
67 if (typeof kValue === 'string') {
68 tag = kValue
69 } else if (isLocaleObject(kValue)) {
70 // For Intl.Locale objects, use toString() which returns the canonicalized locale
71 tag = kValue.toString()
72 } else {
73 throw new TypeError(
74 `Invalid locale type: expected string or Intl.Locale, got ${typeof kValue}`
75 )
76 }
77
78 // Step 7e-g: Validate and canonicalize
79 const canonicalizedTag = emitUnicodeLocaleId(
80 CanonicalizeUnicodeLocaleId(parseUnicodeLocaleId(tag))
81 )
82
83 // Step 7h: Deduplicate
84 if (seen.indexOf(canonicalizedTag) < 0) {
85 seen.push(canonicalizedTag)
86 }

Callers 12

getCanonicalLocalesFunction · 0.70
core.tsFile · 0.50
core.tsFile · 0.50
constructorMethod · 0.50
supportedLocalesOfMethod · 0.50
supportedLocalesOfMethod · 0.50
constructorMethod · 0.50
supportedLocalesOfMethod · 0.50
supportedLocalesOfMethod · 0.50
constructorMethod · 0.50
supportedLocalesOfMethod · 0.50
core.tsFile · 0.50

Calls 5

isLocaleObjectFunction · 0.85
emitUnicodeLocaleIdFunction · 0.85
parseUnicodeLocaleIdFunction · 0.85
toStringMethod · 0.45

Tested by

no test coverage detected