I have following code
var s = storage('foo');
s.bar = 100;
storage('foo', s);
storage returns an object from some storage media. I then change the value of one property of the object and send it to storage again. My question is is there any way to make it a one liner? Something like
storage('foo', storage('foo').bar = 100);
But the above code only saves 100 instead of entire foo object.
Here is the storage function, it stores on localstorage but makes it object storage instead of string storage:
function storage(item, value) {
if(value!=null) {
var result = (storage()) ? storage() : {};
if(item) result[item] = value;
return localStorage.setItem('storage', JSON.stringify(result))
} else return (item) ? storage()[item] : JSON.parse(localStorage.getItem('storage'));
}
Edit:
So I ended up with following one line change in storage function. But this does not account for multidimensional usage. So I will welcome any suggestions.
function storage(item, value, property) {
...
if(item) (property) ? result[item][property] = value : result[item] = value;
...
}
The reasonably thing to do, if you cannot change the
storagefunction, is to create another function:If you can change storage though, this would be an even better way.
jQuery.dataworks similarly.There are ways to do this in (almost) one line, with the help of the comma operator [MDN], but it ain’t pretty:
Since you said
storageis your function, overloading it seems to be a good way. It would go like this:I hope it gives you some idea.