relative-time-format
Version:
A convenient Intl.RelativeTimeFormat polyfill
67 lines (65 loc) • 2.27 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = resolveLocale;
exports.resolveLocaleLookup = resolveLocaleLookup;
var _LocaleDataStore = require("./LocaleDataStore.js");
/**
* Resolves a locale to a supported one (if any).
* @param {string} locale
* @param {Object} [options] - An object that may have the following property:
* @param {string} [options.localeMatcher="lookup"] - The locale matching algorithm to use. Possible values are "lookup" and "best fit". Currently only "lookup" is supported.
* @return {string} [locale]
* @example
* // Returns "sr"
* resolveLocale("sr-Cyrl-BA")
* // Returns `undefined`
* resolveLocale("xx-Latn")
*/
function resolveLocale(locale) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var localeMatcher = options.localeMatcher || 'lookup';
switch (localeMatcher) {
case 'lookup':
return resolveLocaleLookup(locale);
// "best fit" locale matching is not supported.
// https://github.com/catamphetamine/relative-time-format/issues/2
case 'best fit':
// return resolveLocaleBestFit(locale)
return resolveLocaleLookup(locale);
default:
throw new RangeError("Invalid \"localeMatcher\" option: ".concat(localeMatcher));
}
}
/**
* Resolves a locale to a supported one (if any).
* Starts from the most specific locale and gradually
* falls back to less specific ones.
* This is a basic implementation of the "lookup" algorithm.
* https://tools.ietf.org/html/rfc4647#section-3.4
* @param {string} locale
* @return {string} [locale]
* @example
* // Returns "sr"
* resolveLocaleLookup("sr-Cyrl-BA")
* // Returns `undefined`
* resolveLocaleLookup("xx-Latn")
*/
function resolveLocaleLookup(locale) {
var resolvedLocale = (0, _LocaleDataStore.resolveLocale)(locale);
if (resolvedLocale) {
return resolvedLocale;
}
// `sr-Cyrl-BA` -> `sr-Cyrl` -> `sr`.
var parts = locale.split('-');
while (locale.length > 1) {
parts.pop();
locale = parts.join('-');
var _resolvedLocale = (0, _LocaleDataStore.resolveLocale)(locale);
if (_resolvedLocale) {
return _resolvedLocale;
}
}
}
//# sourceMappingURL=resolveLocale.js.map