Add a module to wrap around localStorage and make it handy

This commit is contained in:
Tissevert 2019-11-24 17:52:22 +01:00
parent e5ee61e848
commit cd517821c3
1 changed files with 48 additions and 0 deletions

48
www/save.js Normal file
View File

@ -0,0 +1,48 @@
function Save(modules) {
var save = JSON.parse(localStorage.getItem('save')) || {};
return {
get: get,
set: set
};
function move(coordinates) {
if(coordinates.path.length == 1) {
return coordinates;
} else {
var newFocus = coordinates.focus[coordinates.path[0]];
if (newFocus != undefined) {
var newCoordinates = {path: coordinates.path.slice(1), focus: newFocus};
return move(newCoordinates);
} else {
return coordinates;
}
}
}
function get(key) {
if(key != undefined) {
var outputCoordinates = move({path: key.split('.'), focus: save});
if(outputCoordinates.focus != undefined && outputCoordinates.path.length == 1) {
return outputCoordinates.focus[outputCoordinates.path[0]]
} else {
return null;
}
}
}
function set(key, value) {
if(key != undefined) {
var outputCoordinates = move({path: key.split('.'), focus: save});
while(outputCoordinates.path.length > 1) {
outputCoordinates.focus[outputCoordinates.path[0]] = {};
outputCoordinates.focus = outputCoordinates.focus[outputCoordinates.path[0]];
outputCoordinates.path = outputCoordinates.path.slice(1);
}
outputCoordinates.focus[outputCoordinates.path[0]] = value;
} else {
save = value;
}
localStorage.setItem('save', JSON.stringify(save));
}
}