Skip to content

Instantly share code, notes, and snippets.

@akhawaja
Created October 23, 2016 20:16
Show Gist options
  • Save akhawaja/72b60260eaad919f7b42e4a005caf15c to your computer and use it in GitHub Desktop.
Save akhawaja/72b60260eaad919f7b42e4a005caf15c to your computer and use it in GitHub Desktop.
JavaScript Cookie Manager class.
/**
* Cookie manager.
* @author Amir Khawaja <[email protected]>
* @license MIT
* @constructor
*/
var CookieStore = function () {
/**
* Indicate if value is of type integer.
* @param {*} value - The value to test.
* @returns {boolean}
* @private
*/
this._isInteger = function (value) {
return !isNaN(value) && parseInt(Number(value)) == value && !isNaN(parseInt(value, 10));
}
};
/**
* Get a cookie from the cookie store.
* @param {string} key - The name of the cookie.
* @returns {*}
*/
CookieStore.prototype.get = function (key) {
var k;
return (k = new RegExp('(?:^|;\\s*)' + ('' + key).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') + '=([^;]*)')
.exec(document.cookie)) && k[1];
};
/**
* Set a cookie.
* @param {string} name - The name of the cookie.
* @param {string} value - The value of the cookie.
* @param {int} [days] - The number of days to keep the cookie.
* @param {string} [path] - The path of the cookie.
*/
CookieStore.prototype.set = function (name, value, days, path) {
var expires;
if (days !== void 0 && this._isInteger(days)) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
} else {
expires = "";
}
var dir = path || '/';
document.cookie = name + "=" + value + expires + "; path=" + dir;
};
/**
* Delete a cookie.
* @param {string} key - The name of the cookie.
*/
CookieStore.prototype.delete = function (key) {
this.set(key, '', -1);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment