-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenUtils.js
34 lines (34 loc) · 1.41 KB
/
genUtils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
export function loadLocalStorage(localStorageKey, defaultObject) {
if (testLocalStorage()) {
const storedJson = localStorage.getItem(localStorageKey);
if (storedJson) {
const storedObject = JSON.parse(storedJson);
for (const property in defaultObject) {
if (storedObject.hasOwnProperty(property)) {
const defaultValue = defaultObject[property];
const storedValue = storedObject[property];
if (typeof defaultValue !== typeof storedValue) {
if (typeof defaultValue === 'number') {
defaultObject[property] = parseFloat(storedValue);
} else if (typeof defaultValue === 'boolean') {
defaultObject[property] = storedValue === 'true';
}
} else defaultObject[property] = storedObject[property];
}
}
}
}
return defaultObject;
}
export function saveLocalStorage(localStorageKey, settingsObject) {
if (testLocalStorage()) localStorage.setItem(localStorageKey, JSON.stringify(settingsObject));
}
function testLocalStorage() {
try {
localStorage.setItem("testKey", "testValue");
localStorage.removeItem("testKey");
return true;
} catch (error) {
return false;
}
}