From c8d4307ad86d112ef79cb0162fb77c1f80516100 Mon Sep 17 00:00:00 2001 From: kazuya kawaguchi Date: Fri, 29 Sep 2023 20:09:37 +0900 Subject: [PATCH] feat: add `toLocale` util (#18) * feat: add `toLocale` util * refactor --- README.md | 1 + src/http.ts | 3 ++- src/shared.test.ts | 16 ++++++++++++++++ src/shared.ts | 13 +++++++++++++ 4 files changed, 32 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ccaeac6..951940c 100644 --- a/README.md +++ b/README.md @@ -121,6 +121,7 @@ You can play the below examples: ### Common - `isLocale` +- `toLocale` - `parseAcceptLanguage` - `validateLanguageTag` - `normalizeLanguageName` diff --git a/src/http.ts b/src/http.ts index 1395614..ded2eb9 100644 --- a/src/http.ts +++ b/src/http.ts @@ -4,6 +4,7 @@ import { isURLSearchParams, parseAcceptLanguage, pathLanguageParser, + toLocale, validateLanguageTag, } from './shared.ts' import { ACCEPT_LANGUAGE_HEADER } from './constants.ts' @@ -136,7 +137,7 @@ export function getHeaderLanguagesWithGetter( } export function getLocaleWithGetter(getter: () => string): Intl.Locale { - return new Intl.Locale(getter()) + return toLocale(getter()) } export function validateLocale(locale: string | Intl.Locale): void { diff --git a/src/shared.test.ts b/src/shared.test.ts index 647061d..e319e5f 100644 --- a/src/shared.test.ts +++ b/src/shared.test.ts @@ -5,6 +5,7 @@ import { normalizeLanguageName, parseAcceptLanguage, pathLanguageParser, + toLocale, validateLanguageTag, } from './shared.ts' @@ -18,6 +19,21 @@ describe('isLocale', () => { }) }) +describe('toLocale', () => { + test('language tag', () => { + expect(toLocale('en-US').toString()).toBe('en-US') + }) + + test('Intl.Locale instance', () => { + const locale = new Intl.Locale('en-US') + expect(toLocale(locale).toString()).toBe('en-US') + }) + + test('invalid language tag', () => { + expect(() => toLocale('')).toThrowError(RangeError) + }) +}) + describe('parseAcceptLanguage', () => { test('basic: ja,en-US;q=0.7,en;q=0.3', () => { expect(parseAcceptLanguage('ja,en-US;q=0.7,en;q=0.3')).toEqual([ diff --git a/src/shared.ts b/src/shared.ts index ad31219..219b1d3 100644 --- a/src/shared.ts +++ b/src/shared.ts @@ -20,6 +20,19 @@ export function isLocale(val: unknown): val is Intl.Locale { return toTypeString(val) === '[object Intl.Locale]' } +/** + * returns the {@link Intl.Locale | locale} + * + * @param {string | Intl.Locale} val The value for which the 'locale' is requested. + * + * @throws {RangeError} Throws the {@link RangeError} if `val` is not a well-formed BCP 47 language tag. + * + * @returns {Intl.Locale} The locale + */ +export function toLocale(val: string | Intl.Locale): Intl.Locale { + return isLocale(val) ? val : new Intl.Locale(val) +} + /** * parse `accept-language` header string *