-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
objectify-cookies.js
45 lines (45 loc) · 1.33 KB
/
objectify-cookies.js
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
45
'use strict';
/**
* Builds dictionary/object from cookies string
* @function objectifyCookies
* @param {boolean} coerce_values - If `true` attempts to coerce values
* @return Object
* @throws {!SyntaxError}
* @author S0AndS0
* @license AGPL-3.0
*/
const objectifyCookies = (coerce_values = false) => {
return document.cookie.split(';').reduce((accumulator, cookie) => {
const chunk = cookie.split('=');
const key = chunk[0].trim();
const value = chunk[1].trim();
if (coerce_values === true) {
try {
accumulator[key] = JSON.parse(value);
}
catch (e) {
/* istanbul ignore next */
if (!(e instanceof SyntaxError)) {
throw e;
}
if (['undefined', undefined].includes(value)) {
accumulator[key] = undefined;
}
else if (['NaN', NaN].includes(value)) {
accumulator[key] = NaN;
}
else {
accumulator[key] = value;
}
}
}
else {
accumulator[key] = value;
}
return accumulator;
}, {});
};
/* istanbul ignore next */
if (typeof module !== 'undefined') {
module.exports = objectifyCookies;
}