-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlanguages.ts
More file actions
44 lines (32 loc) · 1.22 KB
/
Copy pathlanguages.ts
File metadata and controls
44 lines (32 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { type WebsiteLanguageId, parseSupportedLanguageString } from '../../common/languages.ts'
import { schwartzMax } from '../../common/support/iteration.ts'
import { type UnitRatio } from '../../common/types/numbers.ts'
export interface IAcceptedLanguage {
languageId: WebsiteLanguageId
weight?: UnitRatio
}
const LANGUAGE_SPEC_REGEX = /^\s*(?<lang>[a-zA-Z0-9-]+)?\s*(;\s*q=(?<weight>(1(.0+)?|0.\d+)))?\s*$/
export function* iterParseAcceptLanguageHeader(header: string): Generator<IAcceptedLanguage> {
for (const spec of header.split(',')) {
const match = spec.match(LANGUAGE_SPEC_REGEX)
if (match === null || match.groups === undefined) {
continue
}
const languageId = parseSupportedLanguageString(match.groups.lang)
if (languageId === undefined) {
continue
}
const result: IAcceptedLanguage = { languageId }
if (match.groups.weight) {
result.weight = Number.parseFloat(match.groups.weight)
}
yield result
}
}
export function parsePreferredLanguage(header: string): WebsiteLanguageId | undefined {
const max = schwartzMax(({ weight }) => weight ?? 1, iterParseAcceptLanguageHeader(header))
if (max === undefined) {
return undefined
}
return max.languageId
}