This code consists of two functions to manipulate cookies; a setCookie()
and a getCookie()
function.
function setCookie(cookieName, cookieValue, expirationDays) {
var expirationDate = new Date();
expirationDate.setDate(expirationDate.getDate() + expirationDays);
cookieValue = cookieValue + '; expires=' + expirationDate.toUTCString();
document.cookie = cookieName + '=' + cookieValue;
}
function getCookie(cookieName) {
var cookies = document.cookie.split(';');
for (let cookie of cookies) {
let index = cookie.indexOf('=');
let key = cookie.substr(0, index);
let val = cookie.substr(index + 1);
if (key.trim() === cookieName) { return val; }
}
}
The original code pollutes the global namespace so here are examples of the same two cookie functions wrapped in different namespace patterns for organization, reuse, and encapsulation