From: Laurent Mazet Date: Wed, 9 Sep 2020 05:32:48 +0000 (+0200) Subject: new functions getSetting and setSetting X-Git-Url: https://secure.softndesign.org/git/?a=commitdiff_plain;h=64c1ebff0c9622662f5be7811a220e7621562cd7;p=trivabble.git new functions getSetting and setSetting --- diff --git a/public/trivabble.js b/public/trivabble.js index 24bf947..f471e06 100644 --- a/public/trivabble.js +++ b/public/trivabble.js @@ -47,6 +47,88 @@ setConf("FLASH_LIGHT_DURATIONS", [800, 1600, 3200]); setConf("FLASH_LIGHT_COLOR", "#E3E"); + function getSetting(key) { + let type = undefined; + let value; + + /* get default value from configuration */ + if (Object.prototype.hasOwnProperty.call(Conf, key)) { + value = Conf[key]; + type = typeof value; + } + + /* try to retrieve value from localstorage */ + if (Object.prototype.hasOwnProperty.call(localStorage, key)) { + value = localStorage.getItem(key); + + /* get type from localStore if no default is set */ + if (type === "undefined") { + type = localStorage.getItem(key + "_type"); + } + + /* cast from string to type */ + if (type === "bigint") { + value = BigInt(value); + } else if (type === "boolean") { + value = (value) ? true : false; + } else if (type === "number") { + value = Number(value); + } else if (type === "object") { + value = JSON.parse(value); + } else if (type === "string") { + value = String(value); + } else { + console.error("Unsupported type"); + } + } + + return value; + } + + function setSetting(key, value) { + let type = undefined; + + /* try to retrieve type from configuration */ + if (Object.prototype.hasOwnProperty.call(Conf, key)) { + type = typeof Conf[key]; + } + + /* try to retrieve type from localstorage */ + if (type === undefined) { + if (Object.prototype.hasOwnProperty.call(localStorage, key)) { + type = localStorage.getItem(key + "_type"); + } + } + + /* if not set type is defined from value */ + if (type === undefined) { + typeof value; + } + + /* storage value in localstorage */ + if (type !== typeof value) { + console.error("incoherent type"); + } else { + if (type === "object") { + value = JSON.stringify(value); + } + if ((type === "bigint") || + (type === "boolean") || + (type === "number") || + (type === "object") || + (type === "string")) { + localStore.setItem(key, value); + + /* store type into localstorage if no default value in configuration */ + if (Object.prototype.hasOwnProperty.call(Conf, key)) { + localStore.setItem(key + "_type", type); + } + } else { + console.error("Unsupported type"); + } + } + } + const _ = (window.libD && libD.l10n) ? libD.l10n() : function (s) { return s; };