From ca5b6579e9efd2d9bf07ba6b6fbab33a585521d3 Mon Sep 17 00:00:00 2001 From: kazuya kawaguchi Date: Fri, 29 Sep 2023 20:05:20 +0900 Subject: [PATCH] feat: add `toLocale` util --- README.md | 1 + src/shared.test.ts | 16 ++++++++++++++++ src/shared.ts | 13 +++++++++++++ 3 files changed, 30 insertions(+) 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/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 *