Last active
December 31, 2015 20:58
-
-
Save hstove/8043323 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Store('score') # undefined | |
#Store('score',1) | |
#Store('score') # 1 | |
#Store('score','',-1) # expires | |
#Store('score') # undefined | |
#Store('score', 1) # 1 | |
#Store('score', -> 2 ) # 1 only calls function if 'score' not found | |
#Store('score','',-1) | |
#Store('score', -> 2 ) # 2 | |
window.Store = -> | |
localStorageSupported = localStorage? | |
createCookie = (name, value, days=3650) -> | |
if days | |
date = new Date | |
date.setTime(date.getTime() + (days*24*60*60*1000)) | |
expires = "; expires=" + date.toGMTString() | |
else | |
expires = "" | |
document.cookie = name + "=" + value + expires + "; path=/" | |
getCookie = (key) -> | |
key += "=" | |
for c in document.cookie.split(';') | |
c.substring(1, c.length) while c.charAt(0) is ' ' | |
return c.substring(key.length, c.length) if c.indexOf(key) == 0 | |
return null | |
methods = if localStorageSupported | |
set: (key, value) -> localStorage[key] = value | |
get: (key) -> localStorage[key] | |
expire: (key) -> localStorage.removeItem(key) | |
else | |
set: (key, value) -> createCookie(key, value, 1) | |
get: getCookie | |
expire: (key) -> createCookie(key, "", -1) | |
switch (a = arguments).length | |
when 0 then methods | |
when 1 then methods.get(a[0]) | |
when 2 | |
if _.isFunction a[1] | |
if methods.get(a[0]) | |
methods.get(a[0]) | |
else | |
methods.set(a[0], a[1]()) | |
else | |
methods.set(a[0],a[1]) | |
when 3 then methods.expire(a[0]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment