Speed up memo stores

This commit is contained in:
Andrew Kingston 2024-08-12 09:55:12 +01:00
parent 304c244943
commit d77e4381cc
No known key found for this signature in database
1 changed files with 8 additions and 17 deletions

View File

@ -4,32 +4,23 @@ import { writable, get, derived } from "svelte/store"
// subscribed children will only fire when a new value is actually set // subscribed children will only fire when a new value is actually set
export const memo = initialValue => { export const memo = initialValue => {
const store = writable(initialValue) const store = writable(initialValue)
let currentJSON = null
const tryUpdateValue = (newValue, currentValue) => { const tryUpdateValue = newValue => {
// Sanity check for primitive equality const newJSON = JSON.stringify(newValue)
if (currentValue === newValue) { if (newJSON !== currentJSON) {
return
}
// Otherwise deep compare via JSON stringify
const currentString = JSON.stringify(currentValue)
const newString = JSON.stringify(newValue)
if (currentString !== newString) {
store.set(newValue) store.set(newValue)
currentJSON = newJSON
} }
} }
return { return {
subscribe: store.subscribe, subscribe: store.subscribe,
set: newValue => { set: tryUpdateValue,
const currentValue = get(store)
tryUpdateValue(newValue, currentValue)
},
update: updateFn => { update: updateFn => {
const currentValue = get(store) let mutableCurrentValue = JSON.parse(currentJSON)
let mutableCurrentValue = JSON.parse(JSON.stringify(currentValue))
const newValue = updateFn(mutableCurrentValue) const newValue = updateFn(mutableCurrentValue)
tryUpdateValue(newValue, currentValue) tryUpdateValue(newValue)
}, },
} }
} }