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
     }
};
\$\endgroup\$
  • \$\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\$ – Joseph Dec 3 '15 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\$ – nikk wong Dec 4 '15 at 2:28
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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.