Skip to content

Commit 8018ea2

Browse files
committed
Change cookie reading approach
Collecting all cookies in a jar, and when looking for a specific one breaking out of the loop. By this we're also sharing one variable less (`result`) for both the write and read functionality, which will make it easier to modularize the library in the future.
1 parent 7f75645 commit 8018ea2

File tree

1 file changed

+5
-12
lines changed

1 file changed

+5
-12
lines changed

src/js.cookie.js

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@
3838

3939
function init (converter) {
4040
function api (key, value, attributes) {
41-
var result;
4241
if (typeof document === 'undefined') {
4342
return;
4443
}
@@ -58,7 +57,7 @@
5857
attributes.expires = attributes.expires ? attributes.expires.toUTCString() : '';
5958

6059
try {
61-
result = JSON.stringify(value);
60+
var result = JSON.stringify(value);
6261
if (/^[\{\[]/.test(result)) {
6362
value = result;
6463
}
@@ -98,10 +97,7 @@
9897

9998
// Read
10099

101-
if (!key) {
102-
result = {};
103-
}
104-
100+
var jar = {};
105101
var decode = function (s) {
106102
return s.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent);
107103
};
@@ -129,18 +125,15 @@
129125
} catch (e) {}
130126
}
131127

128+
jar[name] = cookie;
129+
132130
if (key === name) {
133-
result = cookie;
134131
break;
135132
}
136-
137-
if (!key) {
138-
result[name] = cookie;
139-
}
140133
} catch (e) {}
141134
}
142135

143-
return result;
136+
return key ? jar[key] : jar;
144137
}
145138

146139
api.set = api;

0 commit comments

Comments
 (0)