by
98 11
1
6
230k
1
Top 1% !
Popular
Pearl of Wisdom
Tagged
Specified
OpenSource
Popularity: 6312nd place

Published on:

Languagejavascript
LicenseMIT_X11
OriginFork

DB(store, schema) | Store Data in localStorage

[FORK][ https://www.snip2code.com/Snippet/217248/object-data-store-----stuff-it-in-yer-cl
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/989472/DB(store--schema)---Store-Data-in-localS?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
// Local Data function DB(store, schema) { this.store = store; if (!localStorage[store] || typeof localStorage[store] == 'undefined') { localStorage[store] = JSON.stringify(schema|| {}); } this.setData = function (key, val) { var lda = JSON.parse(localStorage[this.store]); doUpdate(ldta, key, val); localStorage[store] = JSON.stringify(ldta); }; this.getData = function (key) { var ldta = JSON.parse(localStorage[this.store]); if (key) { return pathGet(ldta, key); } return ldta; }; this.reset = function (schema) { localStorage[this.store] = JSON.stringify(schema || {}); }; this.delete = function() { localStorage.removeItem(this.store); }; var doUpdate = function (ob, kStr, val) { var kpth = keyStr.split('.'), i = 0, lstIdx = kpth.length - 1; for (;i < lstIdx; ++i) { var key = kpth[i]; if (!(key in ob)) { ob[key] = {}; } ob = ob[key]; } ob[kpth[lstIdx]] = val; }; var pathGet = function (obj, key, leftOvrs) { if ( leftOvrs === undefined ) { leftOvrs = key.split('.'); } var cur = leftOvrs.shift(); if ( typeof(obj) == 'object' && obj[cur] !== undefined ) { if ( leftOvrs.length === 0 ) { return obj[cur]; } else if ( typeof(obj[cur]) == 'object' ) { return arguments.callee(obj[cur], undefined, leftOvrs); } } return null; }; }
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus