Skip to content

Instantly share code, notes, and snippets.

@ungoldman
Last active March 9, 2016 02:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ungoldman/9902709 to your computer and use it in GitHub Desktop.
Save ungoldman/9902709 to your computer and use it in GitHub Desktop.
Tiny localStorage wrapper (moved to https://github.com/ngoldman/tinystore)
function TinyStore (name) {
this.enabled = (function(){
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
})();
this.session = {};
if (this.enabled) {
try {
this.session = JSON.parse(localStorage.getItem(name)) || {};
} catch (e) {}
}
this.save = function () {
if (this.enabled) {
localStorage.setItem(name, JSON.stringify(this.session));
}
return this.session;
};
this.set = function (key, value) {
this.session[key] = value;
this.save();
return this.session[key];
};
this.get = function (key) {
return this.session[key];
};
this.remove = function (key) {
delete this.session[key];
return this.save();
};
this.clear = function () {
this.session = {};
return this.save();
};
}

TinyStore

Useful for interacting with a persistent namespaced object store within localStorage without messing with anything else that might be there (like on *.github.io).

API

var store = new TinyStore('memories')

store.enabled
// -> true (you've got localStorage!)

store.get('saturday')
// -> undefined

store.set('saturday', 'karaoke')
// -> 'karaoke'

store.set('sunday', ['hangover', 'NaptimePDX'])
// -> ["hangover", "NaptimePDX"]

store.set('monday', { 'work': ['meetings', 'coding'] })
// -> { "work": ["meetings", "coding"] }

store.session
// -> { "saturday": "karaoke", "sunday": ["hangover", "NaptimePDX"], "monday": { "work": ["meetings", "coding"] } }

// you can manipulate the session object directly if that's your jam
store.session.whatever = { 'doge': 'sweater vests' }
store.save()
// -> { "saturday": "karaoke", "sunday": ["hangover", "NaptimePDX"], "monday": { "work": ["meetings", "coding"] }, "whatever": { "doge": "sweater vests" } }

store.remove('whatever')
// -> { "saturday": "karaoke", "sunday": ["hangover", "NaptimePDX"], "monday": { "work": ["meetings", "coding"] } }

store.clear()
// -> {}
@ungoldman
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment