Skip to content

Commit e43f203

Browse files
authored
perf(helper/cookie): fast-path for name specified (#3608)
* 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
1 parent e9830c6 commit e43f203

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

src/utils/cookie.test.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,14 @@ describe('Parse cookie', () => {
3030
expect(cookie['tasty_cookie']).toBeUndefined()
3131
})
3232

33+
it('Should parse one cookie specified by name even if it is not found', () => {
34+
const cookieString = 'yummy_cookie=choco; tasty_cookie = strawberry '
35+
const cookie: Cookie = parse(cookieString, 'no_such_cookie')
36+
expect(cookie['yummy_cookie']).toBeUndefined()
37+
expect(cookie['tasty_cookie']).toBeUndefined()
38+
expect(cookie['no_such_cookie']).toBeUndefined()
39+
})
40+
3341
it('Should parse cookies with no value', () => {
3442
const cookieString = 'yummy_cookie=; tasty_cookie = ; best_cookie= ; last_cookie=""'
3543
const cookie: Cookie = parse(cookieString)

src/utils/cookie.ts

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -77,17 +77,22 @@ const validCookieNameRegEx = /^[\w!#$%&'*.^`|~+-]+$/
7777
const validCookieValueRegEx = /^[ !#-:<-[\]-~]*$/
7878

7979
export const parse = (cookie: string, name?: string): Cookie => {
80+
if (name && cookie.indexOf(name) === -1) {
81+
// Fast-path: return immediately if the demanded-key is not in the cookie string
82+
return {}
83+
}
8084
const pairs = cookie.trim().split(';')
81-
return pairs.reduce((parsedCookie, pairStr) => {
85+
const parsedCookie: Cookie = {}
86+
for (let pairStr of pairs) {
8287
pairStr = pairStr.trim()
8388
const valueStartPos = pairStr.indexOf('=')
8489
if (valueStartPos === -1) {
85-
return parsedCookie
90+
continue
8691
}
8792

8893
const cookieName = pairStr.substring(0, valueStartPos).trim()
8994
if ((name && name !== cookieName) || !validCookieNameRegEx.test(cookieName)) {
90-
return parsedCookie
95+
continue
9196
}
9297

9398
let cookieValue = pairStr.substring(valueStartPos + 1).trim()
@@ -96,10 +101,13 @@ export const parse = (cookie: string, name?: string): Cookie => {
96101
}
97102
if (validCookieValueRegEx.test(cookieValue)) {
98103
parsedCookie[cookieName] = decodeURIComponent_(cookieValue)
104+
if (name) {
105+
// Fast-path: return only the demanded-key immediately. Other keys are not needed.
106+
break
107+
}
99108
}
100-
101-
return parsedCookie
102-
}, {} as Cookie)
109+
}
110+
return parsedCookie
103111
}
104112

105113
export const parseSigned = async (

0 commit comments

Comments
 (0)