Skip to content

Instantly share code, notes, and snippets.

@grid23
Created May 14, 2013 14:15
Show Gist options
  • Select an option

  • Save grid23/5576239 to your computer and use it in GitHub Desktop.

Select an option

Save grid23/5576239 to your computer and use it in GitHub Desktop.
/*
CookieList v0.0.3
v0.0.3 changelog :
- a little faster
- detect if cookie is enabled
- polyfill for max-age attribute, so you don't have to care about it yourself
TODO list :
- get faster
- clean the code (code reuse among methods)
Usage examples :
Example A
cookieList().set('foo', 'bar')
cookieList().remove('foo'}
cookieList().set('cook', 'ie', { domain: '.github.com', maxAge : 60*60*24 })
cookieList().remove('cook', { domain: '.github.com' })
(Notes : you need to remove a cookie with the same domain and path with which it was created first)
Example B
var utma = cookieList().get('__utma')
Example C
var gaCookieList = cookieList().search(/^__utm/)
More examples
// set more than one cookie at a time
cookieList().set('foo', 'bar').set('cook', 'ie') // through chaining
cookieList().set([ ['foo', 'bar'], ['cook', 'ie'] ]) // through an array containing arrays of arguments
cookieList().set([ ['foo', 'bar'], ['cook', 'ie'], ['coo', 'kie', { maxAge: 60*60*24*30 }] ], { maxAge: 60*60*24 })
// First and second cookies will use the same options, while the third will use its own
// getting more than one cookie at a time
cookieList().get(/^__utm/) // is a shortcut for cookieList().search(/^__utm/)
cookieList().get(['__utmv', '__utma'])
// removing more than one cookie at a time
cookieList().remove(/^__utm/) // through regexp
cookieList().remove(['__utmv', '__utma'])
// when mutilple cookies are requested the return looks like :
[
{name : 'foo', value: 'bar'},
{name : 'cook', value: 'ie'},
{name : 'coo', value: 'kie'}
]
*/
;
var cookieList = (function(root){
"use strict"
var
document = root.document
, VERSION = "0.0.3-3"
, toString = Object.prototype.toString
, isArray = (function(){
if ( Array.isArray )
return function(arr){
return Array.isArray(arr)
}
return function(arr){
return toString.call(arr) == '[object Array]'
}
}())
, isRegExp = function(regexp){
return toString.call(regexp) == '[object RegExp]'
}
, isString = function(str) {
return toString.call(str) == '[object String]'
}
, indexOf = (function(){
if ( Array.prototype.indexOf )
return function(arr, search){
return arr.indexOf(search)
}
return function(arr, search){
for ( var i = 0, len = arr.length; i<len; i++ )
if ( arr[i] === search )
return i
return -1
}
}())
, keys = (function(){
if ( Object.keys )
return function(obj, fn){
var keys = Object.keys(obj)
for ( var i=0, len=keys.length; i<len; i++ )
fn(keys[i], obj[keys[i]], i)
}
return function(obj, fn){
var i =0, key
for ( key in obj ) if ( obj.hasOwnProperty(key) )
fn(key, obj[key], i++)
}
}())
, CookieList = function(){
var list = this.list = {}
, cookies = document.cookie.split(/;\s*/)
, cookie, idx, name, value
for ( var i=0, len=cookies.length; i<len; i++)
(function(cookie){
var idx = cookie.search('=')
, name = cookie.split('=',1)
, value = cookie.slice(idx+1)
list[name] = value
}(cookies[i]))
}
, CookieListProto = CookieList.prototype = {
list : {}
, COOKIE_ENABLED : true
, NO_MAX_AGE_SUPPORT : false
, version : VERSION
, set : function(name, value, parameters, noreturn){
if ( isArray(name) ) {
for ( var i=0, len=name.length; i<len; i++ )
if ( isArray(name[i]) )
this.set(name[i][0], name[i][1], name[i][2] || value, true)
return new CookieList
}
var parameters = parameters || {}
, _arr = []
_arr.push([ name, encodeURIComponent(value) ].join('='))
if ( parameters.path)
_arr.push( [ 'path=', parameters.path ].join('') )
if ( parameters.domain)
_arr.push( [ 'domain=', parameters.domain ].join('') )
if ( parameters.maxAge)
if ( !NO_MAX_AGE_SUPPORT )
_arr.push( [ 'max-age=', parameters.maxAge ].join('') )
else
parameters.expires = new Date( new Date().getTime() + parameters.maxAge ).toUTCString()
if ( parameters.expires)
_arr.push( [ 'expires=', parameters.expires ].join('') )
if ( parameters.secure)
_arr.push( 'secure' )
document.cookie = _arr.join(';')
if (!noreturn)
return new CookieList
}
, get : function(name){
if ( isString(name) ) {
if ( !this.list.hasOwnProperty(name) )
return
return decodeURIComponent(this.list[name])
}
if ( isRegExp(name) )
return this.search(name)
if ( isArray(name) ) {
var _arr = []
, _list = this.list
keys(_list, function(key){
if ( !!~indexOf(name, key) )
_arr.push({ name: key, value : decodeURIComponent(_list[key]) })
})
return _arr
}
}
, remove : function(name, parameters){
var _this = this
, parameters = parameters || {}
, _list = this.list
parameters.expires = (new Date(0)).toUTCString()
if ( isString(name) ) {
if ( !this.list.hasOwnProperty(name) )
return new CookieList
return this.set(name, '', parameters )
}
if ( isRegExp(name) ) {
keys(_list, function(key){
if ( key.match(name) )
_this.set(key, '', parameters )
})
return new CookieList
}
if ( isArray(name) ) {
keys(_list, function(key){
if ( !!~indexOf(name, key) )
_this.set(key, '', parameters )
})
return new CookieList
}
}
, contains : function(name){
var _arr, length, result=0
if ( !isArray(name) )
_arr = [name]
else
_arr = name
length = _arr.length
keys(this.list, function(key){
if ( !!~indexOf(_arr, key) )
result++
})
if (result == length)
return true
return false
}
, search : function(regexp){
var regexp = regexp
if ( !isRegExp(regexp) )
if ( isString(regexp) )
regexp = new RegExp(regexp)
else return []
var _arr = []
, _list = this.list
keys(_list, function(key){
if ( key.match(regexp) )
_arr.push({ name: key, value : decodeURIComponent(_list[key]) })
})
return _arr
}
}
, test = (function(){
var test = new CookieList().set('cookieListTMP', 'tmp', {maxAge:-1}).get('cookieListTMP')
if (!test)
return
test = new CookieList().set('cookieListTMP', '', new Date( new Date().getTime() + 100 ).toUTCString()).get('cookieListTMP')
if (test)
CookieList.prototype.NO_MAX_AGE_SUPPORT = true
else
CookieList.prototype.COOKIE_ENABLED = false
}())
return function(){
return new CookieList
}
}(window))
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment