Skip to content

Instantly share code, notes, and snippets.

@ianlintner-wf
Last active December 20, 2019 22:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ianlintner-wf/373c1d7395f81fc4ced18ab42e6a8c96 to your computer and use it in GitHub Desktop.
Save ianlintner-wf/373c1d7395f81fc4ced18ab42e6a8c96 to your computer and use it in GitHub Desktop.
Simple JS Cookie Helper Class
/***
* Cookie Manager Class w/Static Methods
*/
export default class CookieManager {
/***
* Check if value exists in cookie that is a csv list.
*
* @param {string} key
* @param {string} value
* @return {bool}
*/
static setCookieCheckListValueExists(key, value) {
let listOfValues = CookieManager.getCookie(key);
listOfValues = listOfValues ? listOfValues.split(',') : [];
return listOfValues.contains(value);
}
/***
* Add a value if unique to list of values save as cookie.
*
* @param {string} key
* @param {string} value
*/
static setCookieAddUniqueListValue(key, value) {
// Get array of profiled pages from cookie
let listOfValues = CookieManager.getCookie(key);
listOfValues = listOfValues ? listOfValues.split(',') : [];
// test if exists
if (!listOfValues.contains(value)) {
// add if doesn't
listOfValues.push(value);
CookieManager.setCookie(key, listOfValues.join(','));
}
}
/***
* Simple copypasta cookie set value.
*
* @param {string} key
* @param {string} value
* @param expiration_days
*/
static setCookie(key, value, expiration_days = 30) {
let expires_date = new Date();
expires_date.setDate(expires_date.getDate() + expiration_days);
let expires = "expires="+ expires_date.toUTCString();
document.cookie = key + "=" + value + ";" + expires + ";path=/";
}
/***
* Simple copyapasta cookie get value by key.
*
* @param {string} key
* @return {string}
*/
static getCookie(key) {
let name = key + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for(let i = 0; i <ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
}
@ianlintner-wf
Copy link
Author

cookiemonster

@ianlintner-wf
Copy link
Author

ianlintner-wf commented Dec 20, 2019

This is not intended as complex data storage, but simple strings and array strings . For anything beyond a small data sets local storage or database is far superior. More a proof of concept for small or trivial projects. Copy paste and get / set cookies.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment