Last active
December 17, 2015 00:19
-
-
Save achudars/5520437 to your computer and use it in GitHub Desktop.
LocalStorage as REST using JavaScript
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 gets(storage) | |
{ | |
var array; | |
if(!localStorage[storage]) array = []; | |
else array = JSON.parse(localStorage[storage]); | |
return array; | |
} | |
function get(storage, id) | |
{ | |
if(!localStorage[storage]) return false; | |
var array = JSON.parse(localStorage[storage]); | |
var element; | |
for(var i in array) if(array[i]['id'] == id) { element = array[i]; break; } | |
if(!element) return false; | |
return element; | |
} | |
function post(storage, element) | |
{ | |
var array; | |
if(!localStorage[storage]) array = []; | |
else array = JSON.parse(localStorage[storage]); | |
element['id'] = array.length + 1; | |
array.push(element); | |
localStorage[storage] = JSON.stringify(array); | |
return true; | |
} | |
function put(storage, id, option) | |
{ | |
if(!localStorage[storage]) return false; | |
var array = JSON.parse(localStorage[storage]); | |
var element; | |
for(var i in array) if(array[i]['id'] == id) { element = array[i]; break; } | |
for(var key in option) element[key] = option[key]; | |
localStorage[storage] = JSON.stringify(array); | |
return true; | |
} | |
function delete(storage, id) | |
{ | |
if(!localStorage[storage]) return false; | |
var array = JSON.parse(localStorage[storage]); | |
var index = -1; | |
for(var i in array) if(array[i]['id'] == id) { index = i; break; } | |
if(index == -1) return false; | |
array.splice(index, 1); | |
localStorage[storage] = JSON.stringify(array); | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment