Skip to content

Instantly share code, notes, and snippets.

@bellydrum
Last active March 28, 2019 18:19
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 bellydrum/cfc7869243b4d5c4e7ae710ea59edf67 to your computer and use it in GitHub Desktop.
Save bellydrum/cfc7869243b4d5c4e7ae710ea59edf67 to your computer and use it in GitHub Desktop.
Cookie Monster v1.1.1
/**
* cookieHelper.js
* ------------------------------------------------------------------------------
* allows handling of cookies in an object-oriented manner.
* written by bellydrum
* https://gist.github.com/bellydrum/cfc7869243b4d5c4e7ae710ea59edf67
*/
class CookieHelper {
getAsObject(cookieObject={}) {
document.cookie.split('; ').forEach(item => {
cookieObject[item.split('=')[0]] = item.split('=')[1]
})
return cookieObject
}
hasKey(key) {
const cookieObject = this.getAsObject()
return Object.keys(cookieObject).includes(key)
}
addObject(object) {
Object.keys(object).forEach(key => {
document.cookie = `${key}=${object[key]};`
})
}
getObjectByKey(key, returnObject={}) {
returnObject[key] = this.getValueByKey(key)
return returnObject
}
getValueByKey(key) {
const cookieObject = this.getAsObject()
return cookieObject[key]
}
deleteByKey(key) {
document.cookie = key + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;'
}
flush(keys=Object.keys(this.getAsObject())) {
keys.forEach(key => {
this.deleteByKey(key)
})
return this.getAsObject()
}
}
@bellydrum
Copy link
Author

bellydrum commented Mar 28, 2019

I will be updating the methods for v2.0, something along the lines of:

.getAsObject() => .get( cookie=null ) - unifies the two methods and uses cookie as an optional parameter, defaulting to all cookies.
.hasKey( key ) => .has( cookie ) - removes implied word "key".
.addObject() => .add( cookie, value ) - removes implied word "key".
.getValueByKey( key ) => .getValue( cookie ) - removes implied word "key".
.flush( keys=[ e, <...> ] ) => .flush( cookie=null )

I will be DEPRECATING the following methods in v2.0, and subsequently REMOVING them in a future release:

.getObjectByKey() => DEPRECATED in favor of .get( cookie=null ).
.deleteByKey() => DEPRECATED in favor of .flush( cookie=null ).

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