Skip to content

Instantly share code, notes, and snippets.

@bgrayburn
Last active September 1, 2015 13:55
Show Gist options
  • Save bgrayburn/b7561552e58a824dee66 to your computer and use it in GitHub Desktop.
Save bgrayburn/b7561552e58a824dee66 to your computer and use it in GitHub Desktop.
Functions to utilize localStorage as arrays of json objects
initLocalStorageArray = (name)->
if (localStorage.getItem(name)==null)||(localStorage.getItem(name)[0]!='[')
localStorage.setItem(name,'[]')
offlineArrays = ['array1','array2']
offlineArrays.forEach (n)->initLocalStorageArray(n)
clearArrays = ->
offlineArrays.forEach (n)->localStorage.setItem(n,'[]')
addToLocalStorageArray = (name, entry, filt=(->true))->
entries = JSON.parse(localStorage.getItem(name))
entries = _.filter entries, filt
entries.push _.omit(entry, '_id')
localStorage.setItem(name, JSON.stringify(entries))
getFromLocalStorageArray = (name, filt=(->true))->
entries = _.values JSON.parse(localStorage.getItem(name))
entries = _.filter entries, filt
return entries
setLocalStorageArray = (name, val)->
localStorage.setItem(name, JSON.stringify(val))
removeFromLocalStorageArray = (name, val)->
out = []
entries = _.values JSON.parse(localStorage.getItem(name))
_.each entries, (e)->
if !Meteor.util.deepCompare(e, val)
out.push(e)
localStorage.setItem(name, JSON.stringify(out))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment