-
Notifications
You must be signed in to change notification settings - Fork 80
make acceptedLanguages order the header by q values descending #262
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
base: main
Are you sure you want to change the base?
Changes from 1 commit
9458970
9c70026
8261356
da95789
4495e16
c60aacb
6e78127
adbc32d
fc62da6
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,24 @@ | ||
export default function acceptedLanguages(string = "") { | ||
if (typeof string !== "string") { | ||
export default function acceptedLanguages(acceptLanguageHeader = "") { | ||
if (typeof acceptLanguageHeader !== "string") { | ||
throw new TypeError("Argument must be a string"); | ||
} | ||
const tokens = string.split(",").map(t => t.trim()); | ||
return tokens.filter(t => t !== "").map(t => t.split(";")[0]); | ||
const tokens = acceptLanguageHeader.split(",").map(t => t.trim()); | ||
const langsWithQ = []; | ||
tokens.filter(t => t !== "").forEach((t, index) => { | ||
const langWithQ = t.split(";").map(u => u.trim()); | ||
if (langWithQ[0].length > 0) { | ||
|
||
let q = 1.0; | ||
if (langWithQ.length > 1) { | ||
const qVal = langWithQ[1].split("=").map(u => u.trim()); | ||
if (qVal.length === 2 && qVal[0].toLowerCase() === "q") { | ||
const qn = Number(qVal[1]); | ||
q = !isNaN(qn) ? qn : q; | ||
|
||
} | ||
} | ||
langsWithQ.push({ index: index, lang: langWithQ[0], q }); | ||
} | ||
}); | ||
// order by q descending, keeping the header order for equal weights | ||
langsWithQ.sort((a, b) => a.q === b.q ? a.index - b.index : b.q - a.q); | ||
|
||
return langsWithQ.map(t => t.lang); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can you please move the filter to line 5 together with trimming?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
done