Skip to content

Instantly share code, notes, and snippets.

@bellydrum
Last active November 18, 2024 18:51
Show Gist options
  • 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() {
for (const key of Object.keys(this.getAsObject())) {
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