new functions getSetting and setSetting

This commit is contained in:
Laurent Mazet 2020-09-09 07:32:48 +02:00
parent 9c0b1d068e
commit 64c1ebff0c
1 changed files with 82 additions and 0 deletions

View File

@ -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;
};