Skip to content

Commit

Permalink
Change cookie reading approach
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
carhartl committed Feb 16, 2018
1 parent 7f75645 commit 8018ea2
Showing 1 changed file with 5 additions and 12 deletions.
17 changes: 5 additions & 12 deletions src/js.cookie.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@

function init (converter) {
function api (key, value, attributes) {
var result;
if (typeof document === 'undefined') {
return;
}
Expand All @@ -58,7 +57,7 @@
attributes.expires = attributes.expires ? attributes.expires.toUTCString() : '';

try {
result = JSON.stringify(value);
var result = JSON.stringify(value);
if (/^[\{\[]/.test(result)) {
value = result;
}
Expand Down Expand Up @@ -98,10 +97,7 @@

// Read

if (!key) {
result = {};
}

var jar = {};
var decode = function (s) {
return s.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent);
};
Expand Down Expand Up @@ -129,18 +125,15 @@
} catch (e) {}
}

jar[name] = cookie;

if (key === name) {
result = cookie;
break;
}

if (!key) {
result[name] = cookie;
}
} catch (e) {}
}

return result;
return key ? jar[key] : jar;
}

api.set = api;
Expand Down

0 comments on commit 8018ea2

Please sign in to comment.