Skip to content

Commit

Permalink
feat: add toLocale util (#18)
Browse files Browse the repository at this point in the history
* feat: add `toLocale` util

* refactor
  • Loading branch information
kazupon committed Sep 29, 2023
1 parent 6c8a28a commit c8d4307
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 1 deletion.
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
3 changes: 2 additions & 1 deletion src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
isURLSearchParams,
parseAcceptLanguage,
pathLanguageParser,
toLocale,
validateLanguageTag,
} from './shared.ts'
import { ACCEPT_LANGUAGE_HEADER } from './constants.ts'
Expand Down Expand Up @@ -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 {
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 c8d4307

Please sign in to comment.