I am writing a module that can access localStorage
through a public API which exposes methods that allow string or array returns.
It doesn't feel as though I'm doing this in the most effective way. For example, I feel as though using:
var tudCache = getTud();
to grab the object from getTud()
doesn't feel like the most correct implementation.
I'm inclined to use an if
statement i.e. if(getTud().isSuccessful)
to check the conditional but then I would have to re-execute getTud().result
to return the result inside that conditional, causing the getTud()
function to be called twice.
Does anyone have any thoughts?
_self.getTudCache = function () {
// returns an object. {'isSuccessful': boolean, 'result': String}
function getTud() {
return localstorage.getItem(tudStorageKey);
}
function getString() {
var tudCache = getTud();
if (tudCache.isSuccessful)
return tudCache.result;
return "";
}
function getArr() {
var tudCache = getTud();
if (tudCache.isSuccessful)
return JSON.parse(tudCache.result)[tudCacheKey];
return [];
}
return {
getString: getString,
getArr: getArr
}
};
1 Answer 1
It seems to me that it'd be simpler to always use JSON, rather than limit yourself to strings and arrays, specifically.
E.g.
function retrieve(key) {
var json = localStorage.getItem(key);
try {
return JSON.parse(json).value;
} catch(e) {
return json; // either null or a non-comforming value
}
}
function store(key, value) {
var json = JSON.stringify({ value: value });
localStorage.setItem(key, json);
}
This will let you store and retrieve any JSON-serializable value including strings and arrays. You can wrap/namespace it however you like.
localStorage.getItem
return strings, not objects. Can you add in the rest of the code, as well as a simple demo? \$\endgroup\$localStorage
. See this plnkr: plnkr.co/edit/y7eS0R22g0dRkbG4U3US?p=catalogue Thanks! \$\endgroup\$