summaryrefslogtreecommitdiff
path: root/node_modules/bcp-47/lib/stringify.js
blob: e5b367ae760ccf581a1802e29ad619509f89311c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
 * @typedef {Partial<import('./parse.js').Schema>} Schema
 * @typedef {Partial<import('./parse.js').Extension>} Extension
 */

/**
 * Compile a language schema to a BCP 47 language tag.
 *
 * @param {Schema} schema
 * @returns {string}
 */
export function stringify(schema = {}) {
  /** @type {Array<string>} */
  let result = []

  if (schema.irregular) {
    return schema.irregular
  }

  if (schema.regular) {
    return schema.regular
  }

  if (schema.language) {
    result = result.concat(
      schema.language,
      schema.extendedLanguageSubtags || [],
      schema.script || [],
      schema.region || [],
      schema.variants || []
    )

    const values = schema.extensions || []
    let index = -1

    while (++index < values.length) {
      const value = values[index]

      if (value.singleton && value.extensions && value.extensions.length > 0) {
        result.push(value.singleton, ...value.extensions)
      }
    }
  }

  if (schema.privateuse && schema.privateuse.length > 0) {
    result.push('x', ...schema.privateuse)
  }

  return result.join('-')
}