Skip to content

Instantly share code, notes, and snippets.

@topliceanu
Created March 3, 2012 11:05
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 topliceanu/1965560 to your computer and use it in GitHub Desktop.
Save topliceanu/1965560 to your computer and use it in GitHub Desktop.
store data in localstorage, api similar to document databases
// stores arrays binded to keys in localstorage
(function (win) {
var isStorage = function (obj) {
return (Object.prototype.toString.call(obj) === '[object Storage]');
};
var decode = function (str) {
try {
var arr = JSON.parse(str);
if (!Array.isArray(arr)) return false;
return arr;
}
catch (ex) {
console.log(ex);
return false;
}
};
var store = isStorage(win.localStorage) && win.localStorage;
var exists = function (collection, doc) {
if (!store) return false;
var list = decode(store.getItem(collection));
return (list && list.indexOf(doc) !== -1);
};
var save = function (collection, doc) {
if (!store) return false;
if (exists(collection, doc)) return true;
var list = decode(store.getItem(collection));
if (!list) list = [doc];
else list.push(doc);
store.setItem(collection, JSON.stringify(list));
return true;
};
win.docstore = { save: save, exists: exists };
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment