feat: polish code

This commit is contained in:
KaiyiWing
2023-05-13 12:46:51 +08:00
parent f32ef30dc8
commit 7fd170994a

View File

@@ -12,15 +12,32 @@ export default function atomForConfig<T extends Record<string, unknown>>(
return atom((get) => {
// Get the underlying object
const config = get(storageAtom)
// Check if there are missing properties
let hasMissingProperty = false
for (const key in defaultValue) {
if (!(key in config)) {
hasMissingProperty = true
break
let newConfig: T
// Check if the types are different
const isTypeMismatch = typeof config !== typeof defaultValue
if (isTypeMismatch) {
newConfig = defaultValue
} else {
// Check if there are missing properties
let hasMissingProperty = false
for (const key in defaultValue) {
if (!(key in config)) {
hasMissingProperty = true
break
}
}
newConfig = hasMissingProperty ? { ...defaultValue, ...config } : config
}
// Merge iff there are missing properties
return hasMissingProperty ? { ...defaultValue, ...config } : config
if (newConfig !== config) {
const jsonString = JSON.stringify(newConfig)
localStorage.setItem(key, jsonString)
}
return newConfig
}, storageAtom.write)
}