Skip to content

Instantly share code, notes, and snippets.

@sampritipanda
Created January 11, 2017 23:10
Show Gist options
  • Save sampritipanda/d1f03ff2041d0a7a8cf08406cd26ae19 to your computer and use it in GitHub Desktop.
Save sampritipanda/d1f03ff2041d0a7a8cf08406cd26ae19 to your computer and use it in GitHub Desktop.
Draft Model for interacting with LocalStorage
var draft_model = (function () {
var exports = {};
// the key that the drafts are stored under.
var KEY = "drafts";
var ls = localstorage();
ls.version = 1;
function createKey () {
// use the base16 of the current time + a random string to reduce
// collisions to essentially zero.
return new Date().getTime().toString(16) + "-" + Math.random().toString(16).split(/\./).pop();
}
function get () {
return ls.get(KEY) || {};
}
exports.get = get;
exports.getDraft = function (id) {
return get()[id] || false;
}
function save (drafts) {
ls.set(KEY, drafts);
}
exports.addDraft = function (draft) {
var drafts = get();
var id = fn.createKey();
draft.updatedAt = new Date().getTime();
drafts[id] = draft;
save(drafts);
return id;
}
exports.editDraft = function (id, draft) {
var drafts = get();
if (drafts[id]) {
draft.updatedAt = new Date().getTime();
drafts[id] = draft;
save(drafts);
}
}
exports.deleteDraft = function (id) {
var drafts = get();
delete drafts[id];
save(drafts);
}
return exports;
}());
exports.draft_model = draft_model;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment