Skip to content

Commit

Permalink
feat: add toLocale util
Browse files Browse the repository at this point in the history
  • Loading branch information
kazupon committed Sep 29, 2023
1 parent 6c8a28a commit ca5b657
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ You can play the below examples:
### Common

- `isLocale`
- `toLocale`
- `parseAcceptLanguage`
- `validateLanguageTag`
- `normalizeLanguageName`
Expand Down
16 changes: 16 additions & 0 deletions src/shared.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
normalizeLanguageName,
parseAcceptLanguage,
pathLanguageParser,
toLocale,
validateLanguageTag,
} from './shared.ts'

Expand All @@ -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([
Expand Down
13 changes: 13 additions & 0 deletions src/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand Down

0 comments on commit ca5b657

Please sign in to comment.