Skip to content

Commit

Permalink
perf: parseAccept without spread operator (#3003)
Browse files Browse the repository at this point in the history
* perf: parseAccept without spread operator

* fix: format

* fix: review
  • Loading branch information
Jayllyz authored Jun 23, 2024
1 parent d383e49 commit 60d68ca
Showing 1 changed file with 15 additions and 7 deletions.
22 changes: 15 additions & 7 deletions src/helper/accepts/accepts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,22 @@ export const parseAccept = (acceptHeader: string): Accept[] => {
// Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
const accepts = acceptHeader.split(',') // ['text/html', 'application/xhtml+xml', 'application/xml;q=0.9', 'image/webp', '*/*;q=0.8']
return accepts.map((accept) => {
const [type, ...params] = accept.trim().split(';') // ['application/xml', 'q=0.9']
const q = params.find((param) => param.startsWith('q=')) // 'q=0.9'
const parts = accept.trim().split(';') // ['text/html', 'q=0.9', 'image/webp']
const type = parts[0] // text/html
const params = parts.slice(1) // ['q=0.9', 'image/webp']
const q = params.find((param) => param.startsWith('q='))

const paramsObject = params.reduce((acc, param) => {
const keyValue = param.split('=')
const key = keyValue[0].trim()
const value = keyValue[1].trim()
acc[key] = value
return acc
}, {} as { [key: string]: string })

return {
type,
params: params.reduce((acc, param) => {
const [key, value] = param.split('=')
return { ...acc, [key.trim()]: value.trim() }
}, {}),
type: type,
params: paramsObject,
q: q ? parseFloat(q.split('=')[1]) : 1,
}
})
Expand Down

0 comments on commit 60d68ca

Please sign in to comment.