Last active
October 8, 2015 08:28
-
-
Save nstadigs/3305367 to your computer and use it in GitHub Desktop.
localStorage ORM
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
(function(exports) { | |
var mod = function (databaseName, saveInterval) { | |
var self; | |
saveInterval = saveInterval || 2000; | |
databaseName = databaseName || 'unnamed'; | |
this.hasChanged = false; | |
this.store = {}; | |
if (typeof exports.localStorage === 'object') { | |
self = this; | |
this.hasLocalStorage = true; | |
databaseName = 'localStorageORM/' + databaseName; | |
if (exports.localStorage.getItem(databaseName)) { | |
this.store = JSON.parse(exports.localStorage.getItem(databaseName)); | |
} | |
setInterval(function() { | |
if (self.hasChanged) { | |
exports.localStorage.setItem(databaseName, JSON.stringify(self.store)); | |
self.hasChanged = false; | |
} | |
}, saveInterval); | |
} | |
} | |
mod.fn = mod.prototype; | |
mod.fn.get = function (key) { | |
return this.store[key]; | |
}; | |
mod.fn.set = function (key, data) { | |
this.store[key] = data; | |
this.hasChanged = true; | |
}; | |
mod.fn.find = function (attribute, value) { | |
var i, iMax, result; | |
result = []; | |
for (i = 0, iMax = this.store.length; i < iMax; i++) { | |
if (this.store[i][attribute] && this.store[i][attribute] === value) { | |
result.push(this.store[i]); | |
} | |
} | |
return result; | |
}; | |
mod.fn.each = function (callback) { | |
var key; | |
for (key in this.store) { | |
if (this.store.hasOwnProperty(key)) { | |
callback.bind(this, key, this.store[key]); | |
} | |
} | |
}; | |
exports.localStorageORM = mod; | |
}(window)); | |
/******************* | |
Usage | |
*******************/ | |
// Initiate | |
var users = new localStorageORM("users" /* database name */, 1000 /* save interval in ms */); | |
// Set value to key | |
users.set("eva" /* key */, {hair: "brown", eyes: "green"} /* value */); | |
// Get value by key | |
eva = users.get("eva" /*key */); | |
// Get an array of documents by attribute. | |
brownHairedPeople = users.find("hair" /* attribute */, "brown" /* value */); | |
// For each document, call a function | |
users.each(function(key, data) { | |
console.log(key, data); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment