From bcabb0dd78770055f756c1470c68a9b5c62d1efe Mon Sep 17 00:00:00 2001 From: kazuya kawaguchi Date: Wed, 20 Sep 2023 12:44:48 +0900 Subject: [PATCH] feat: add `parseAcceptLanguage` (#2) --- deno/mod.ts | 1 + mod.ts | 3 +++ src/index.ts | 13 +++++++++++++ test/index.test.ts | 33 ++++++++++++++++++++++++++++++++- 4 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 mod.ts diff --git a/deno/mod.ts b/deno/mod.ts index fc5653f..d9e6183 100644 --- a/deno/mod.ts +++ b/deno/mod.ts @@ -1 +1,2 @@ +// TODO: we must change package structure for deno export * from '../src/index.ts' diff --git a/mod.ts b/mod.ts new file mode 100644 index 0000000..7f67017 --- /dev/null +++ b/mod.ts @@ -0,0 +1,3 @@ +import { isLocale } from 'https://deno.land/x/intlify_utils' + +console.log('isLocale', isLocale(new Intl.Locale('en-US'))) diff --git a/src/index.ts b/src/index.ts index 0e9b1b3..50ecb93 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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} 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 === '') + ) +} diff --git a/test/index.test.ts b/test/index.test.ts index ad5cc2a..e2930d0 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -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', () => { @@ -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([]) + }) +})