mirror of
https://github.com/RealKai42/qwerty-learner.git
synced 2026-04-04 22:09:04 +08:00
feat: polish code
This commit is contained in:
@@ -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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user