Skip to content

Commit

Permalink
perf(helper/cookie): fast-path for name specified (#3608)
Browse files Browse the repository at this point in the history
* perf(helper/cookie): fast-path for a specific key

* perf(helper/cookie): fast-path for a specific key not found

* perf(helper/cookie): added test for missing case

* perf(helper/cookie): fix tests

* perf(helper/cookie): fix tests

* perf(helper/cookie): cleanup tests
  • Loading branch information
exoego authored Nov 2, 2024
1 parent e9830c6 commit e43f203
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
8 changes: 8 additions & 0 deletions src/utils/cookie.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@ describe('Parse cookie', () => {
expect(cookie['tasty_cookie']).toBeUndefined()
})

it('Should parse one cookie specified by name even if it is not found', () => {
const cookieString = 'yummy_cookie=choco; tasty_cookie = strawberry '
const cookie: Cookie = parse(cookieString, 'no_such_cookie')
expect(cookie['yummy_cookie']).toBeUndefined()
expect(cookie['tasty_cookie']).toBeUndefined()
expect(cookie['no_such_cookie']).toBeUndefined()
})

it('Should parse cookies with no value', () => {
const cookieString = 'yummy_cookie=; tasty_cookie = ; best_cookie= ; last_cookie=""'
const cookie: Cookie = parse(cookieString)
Expand Down
20 changes: 14 additions & 6 deletions src/utils/cookie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,17 +77,22 @@ const validCookieNameRegEx = /^[\w!#$%&'*.^`|~+-]+$/
const validCookieValueRegEx = /^[ !#-:<-[\]-~]*$/

export const parse = (cookie: string, name?: string): Cookie => {
if (name && cookie.indexOf(name) === -1) {
// Fast-path: return immediately if the demanded-key is not in the cookie string
return {}
}
const pairs = cookie.trim().split(';')
return pairs.reduce((parsedCookie, pairStr) => {
const parsedCookie: Cookie = {}
for (let pairStr of pairs) {
pairStr = pairStr.trim()
const valueStartPos = pairStr.indexOf('=')
if (valueStartPos === -1) {
return parsedCookie
continue
}

const cookieName = pairStr.substring(0, valueStartPos).trim()
if ((name && name !== cookieName) || !validCookieNameRegEx.test(cookieName)) {
return parsedCookie
continue
}

let cookieValue = pairStr.substring(valueStartPos + 1).trim()
Expand All @@ -96,10 +101,13 @@ export const parse = (cookie: string, name?: string): Cookie => {
}
if (validCookieValueRegEx.test(cookieValue)) {
parsedCookie[cookieName] = decodeURIComponent_(cookieValue)
if (name) {
// Fast-path: return only the demanded-key immediately. Other keys are not needed.
break
}
}

return parsedCookie
}, {} as Cookie)
}
return parsedCookie
}

export const parseSigned = async (
Expand Down

0 comments on commit e43f203

Please sign in to comment.