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
}
};
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\$