0
\$\begingroup\$

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
 }
};
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Dec 3, 2015 at 23:22
\$\endgroup\$
2
  • \$\begingroup\$ I'm not even sure this code works. localStorage.getItem return strings, not objects. Can you add in the rest of the code, as well as a simple demo? \$\endgroup\$ Commented Dec 3, 2015 at 23:59
  • \$\begingroup\$ I should have clarified that we're using a wrapper for localStorage. See this plnkr: plnkr.co/edit/y7eS0R22g0dRkbG4U3US?p=catalogue Thanks! \$\endgroup\$ Commented Dec 4, 2015 at 2:28

1 Answer 1

2
\$\begingroup\$

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.

answered Dec 6, 2015 at 11:25
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.