Created
December 5, 2012 13:19
-
-
Save alexaivars/4215454 to your computer and use it in GitHub Desktop.
Simple localstorage polyfill
This file contains hidden or 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
################################################################################ | |
# | |
# [global] localstorage | |
# A simple cookie based polyfill for localStorage | |
# | |
################################################################################ | |
unless Modernizr.localstorage | |
window.localStorage = | |
length: 0 | |
setItem: (key, value) -> | |
days = 365 | |
date = undefined | |
expires = undefined | |
if days | |
date = new Date() | |
date.setTime date.getTime() + (days * 24 * 60 * 60 * 1000) | |
expires = "; expires=" + date.toGMTString() | |
else | |
expires = "" | |
document.cookie = key + "=" + value + expires + "; path=/" | |
@length++ | |
getItem: (key) -> | |
keyEQ = key + "=" | |
ca = document.cookie.split(";") | |
i = 0 | |
len = ca.length | |
while i < len | |
c = ca[i] | |
c = c.substring(1, c.length) while c.charAt(0) is " " | |
return c.substring(keyEQ.length, c.length) if c.indexOf(keyEQ) is 0 | |
i++ | |
null | |
# | |
# Todo: add listAllItems api. | |
# | |
removeItem: (key) -> | |
@setItem key, "", -1 | |
@length-- | |
clear: -> | |
# Caution: will clear all persistent cookies as well | |
ca = document.cookie.split(";") | |
i = 0 | |
len = ca.length | |
while i < len | |
c = ca[i] | |
c = c.substring(1, c.length) while c.charAt(0) is " " | |
key = c.substring(0, c.indexOf("=")) | |
@removeItem key | |
i++ | |
@length = 0 | |
key: (n) -> | |
ca = document.cookie.split(";") | |
return null if n >= ca.length or isNaN(parseFloat(n)) or not isFinite(n) | |
c = ca[n] | |
c = c.substring(1, c.length) while c.charAt(0) is " " | |
c.substring 0, c.indexOf("=") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment