Skip to content

Commit

Permalink
feat: add parseAcceptLanguage (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
kazupon authored Sep 20, 2023
1 parent 1bdde00 commit bcabb0d
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 1 deletion.
1 change: 1 addition & 0 deletions deno/mod.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
// TODO: we must change package structure for deno
export * from '../src/index.ts'
3 changes: 3 additions & 0 deletions mod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { isLocale } from 'https://deno.land/x/intlify_utils'

console.log('isLocale', isLocale(new Intl.Locale('en-US')))
13 changes: 13 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,16 @@ const toTypeString = (value: unknown): string => objectToString.call(value)
export function isLocale(val: unknown): val is Intl.Locale {
return toTypeString(val) === '[object Intl.Locale]'
}

/**
* parse `accept-language` header string
*
* @param {string} value The accept-language header string
*
* @returns {Array<string>} The array of language tags, if `*` (any language) or empty string is detected, return an empty array.
*/
export function parseAcceptLanguage(value: string): string[] {
return value.split(',').map((tag) => tag.split(';')[0]).filter((tag) =>
!(tag === '*' || tag === '')
)
}
33 changes: 32 additions & 1 deletion test/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, test } from 'vitest'
import { isLocale } from '../src/index.ts'
import { isLocale, parseAcceptLanguage } from '../src/index.ts'

describe('isLocale', () => {
test('Locale instance', () => {
Expand All @@ -10,3 +10,34 @@ describe('isLocale', () => {
expect(isLocale('en-US')).toBe(false)
})
})

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([
'ja',
'en-US',
'en',
])
})

test('q-factor nothing: ja,en-US', () => {
expect(parseAcceptLanguage('ja,en-US')).toEqual([
'ja',
'en-US',
])
})

test('single: ja', () => {
expect(parseAcceptLanguage('ja')).toEqual([
'ja',
])
})

test('any language: *', () => {
expect(parseAcceptLanguage('*')).toEqual([])
})

test('empty: ""', () => {
expect(parseAcceptLanguage('')).toEqual([])
})
})

0 comments on commit bcabb0d

Please sign in to comment.