UNPKG

2.72 kBJavaScriptView Raw
1function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
2
3/**
4 * Chooses the most appropriate locale
5 * (one of the registered ones)
6 * based on the list of preferred `locales` supplied by the user.
7 *
8 * @param {string[]} locales - the list of preferable locales (in [IETF format](https://en.wikipedia.org/wiki/IETF_language_tag)).
9 * @param {Function} isLocaleDataAvailable - tests if a locale is available.
10 *
11 * @returns {string} The most suitable locale.
12 *
13 * @example
14 * // Returns 'en'
15 * chooseLocale(['en-US'], undefined, (locale) => locale === 'ru' || locale === 'en')
16 */
17export default function chooseLocale(locales, isLocaleDataAvailable) {
18 // This is not an intelligent algorithm,
19 // but it will do for this library's case.
20 // `sr-Cyrl-BA` -> `sr-Cyrl` -> `sr`.
21 for (var _iterator = locales, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
22 var _ref;
23
24 if (_isArray) {
25 if (_i >= _iterator.length) break;
26 _ref = _iterator[_i++];
27 } else {
28 _i = _iterator.next();
29 if (_i.done) break;
30 _ref = _i.value;
31 }
32
33 var locale = _ref;
34
35 if (isLocaleDataAvailable(locale)) {
36 return locale;
37 }
38
39 var parts = locale.split('-');
40
41 while (parts.length > 1) {
42 parts.pop();
43 locale = parts.join('-');
44
45 if (isLocaleDataAvailable(locale)) {
46 return locale;
47 }
48 }
49 }
50
51 throw new Error("No locale data has been registered for any of the locales: ".concat(locales.join(', ')));
52}
53/**
54 * Whether can use `Intl.DateTimeFormat` for these `locales`.
55 * Returns the first suitable one.
56 * @param {(string|string[])} locales
57 * @return {?string} The first locale that can be used.
58 */
59
60export function intlDateTimeFormatSupportedLocale(locales) {
61 /* istanbul ignore else */
62 if (intlDateTimeFormatSupported()) {
63 return Intl.DateTimeFormat.supportedLocalesOf(locales)[0];
64 }
65}
66/**
67 * Whether can use `Intl.DateTimeFormat`.
68 * @return {boolean}
69 */
70
71export function intlDateTimeFormatSupported() {
72 // Babel transforms `typeof` into some "branches"
73 // so istanbul will show this as "branch not covered".
74
75 /* istanbul ignore next */
76 var isIntlAvailable = (typeof Intl === "undefined" ? "undefined" : _typeof(Intl)) === 'object';
77 return isIntlAvailable && typeof Intl.DateTimeFormat === 'function';
78}
79//# sourceMappingURL=locale.js.map
\No newline at end of file