Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add parseAcceptLanguage #2

Merged
merged 1 commit into from
Sep 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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([])
})
})