From 90057c2415994bc97339e99fd1a23621449eacf3 Mon Sep 17 00:00:00 2001 From: paulmartimx Date: Fri, 24 Apr 2020 13:30:52 -0500 Subject: [PATCH] Allow default value in get() Proposal: Modification to get() method to allow a default value that will be returned if "key" is not present in localStorage ( ls.getItem(key) === null ) --- LocalStorageHandler.js | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/LocalStorageHandler.js b/LocalStorageHandler.js index 04c4c95..de0d898 100644 --- a/LocalStorageHandler.js +++ b/LocalStorageHandler.js @@ -27,13 +27,15 @@ /** * @method get * @param key {String} Item key + * @param def_val {String|Object} Default Value * @return {String|Object|Null} */ - this.get = function(key) { + this.get = function(key, def_val) { + def_val = (typeof def_val === 'undefined') ? null : def_val; try { - return JSON.parse(_ls.getItem(key)); + return JSON.parse(_ls.getItem(key)) || def_val; } catch(e) { - return _ls.getItem(key); + return _ls.getItem(key) || def_val; } };