UNPKG

2.17 kBJavaScriptView Raw
1let getParentLocale = require('./locales').getParentLocale;
2let hasNumbersFields = require('./locales').hasNumbersFields;
3let normalizeLocale = require('./locales').normalizeLocale;
4
5module.exports = function extractNumbersFields(locales) {
6 let cache = {};
7
8 // Loads and caches the numbers fields for a given `locale` because loading
9 // and transforming the data is expensive.
10 function getNumbers(locale) {
11 let numbers = cache[locale];
12 if (numbers) {
13 return numbers;
14 }
15 if (hasNumbersFields(locale)) {
16 numbers = cache[locale] = loadNumbers(locale);
17 return numbers;
18 }
19 }
20
21 // This will traverse the hierarchy for the
22 // given `locale` until it finds an ancestor with numbers fields.
23 function findLocaleWithNumbersFields(locale) {
24 // The "root" locale is the top level ancestor.
25 if (locale === 'root') {
26 return 'root';
27 }
28
29 if (hasNumbersFields(locale)) {
30 return locale;
31 }
32
33 // When the `locale` doesn't have numbers fields, we need to traverse up
34 // its hierarchy to find suitable numbers fields data.
35 return findLocaleWithNumbersFields(getParentLocale(locale));
36 }
37
38 return locales.reduce((numbers, locale) => {
39 locale = normalizeLocale(locale);
40
41 // Walk the `locale`'s hierarchy to look for suitable ancestor with the
42 // date calendars. If no ancestor is found, the given
43 // `locale` will be returned.
44 let resolvedLocale = findLocaleWithNumbersFields(locale);
45
46 // Add an entry for the `locale`, which might be an ancestor. If the
47 // locale doesn't have relative fields, then we fallback to the "root"
48 // locale's fields.
49 numbers[locale] = {
50 numbers: getNumbers(resolvedLocale),
51 };
52
53 return numbers;
54 }, {});
55};
56
57function loadNumbers(locale) {
58 return Object.assign(
59 require('cldr-numbers-full/main/' + locale + '/numbers.json').main[locale].numbers,
60 require('cldr-numbers-full/main/' + locale + '/currencies.json').main[locale].numbers
61 );
62}