budibase/packages/frontend-core/src/utils/memo.js

35 lines
1.0 KiB
JavaScript
Raw Normal View History

import { writable, get, derived } from "svelte/store"
// A simple svelte store which deeply compares all changes and ensures that
// subscribed children will only fire when a new value is actually set
export const memo = initialValue => {
const store = writable(initialValue)
2024-08-20 16:29:39 +02:00
let currentJSON = JSON.stringify(initialValue)
2024-08-12 10:55:12 +02:00
const tryUpdateValue = newValue => {
const newJSON = JSON.stringify(newValue)
if (newJSON !== currentJSON) {
store.set(newValue)
2024-08-12 10:55:12 +02:00
currentJSON = newJSON
}
}
return {
subscribe: store.subscribe,
2024-08-12 10:55:12 +02:00
set: tryUpdateValue,
update: updateFn => {
2024-08-12 10:55:12 +02:00
let mutableCurrentValue = JSON.parse(currentJSON)
const newValue = updateFn(mutableCurrentValue)
2024-08-12 10:55:12 +02:00
tryUpdateValue(newValue)
},
}
}
// Enriched version of svelte's derived store which returns a memo
export const derivedMemo = (store, derivation) => {
const derivedStore = derived(store, derivation)
const memoStore = memo(get(derivedStore))
derivedStore.subscribe(memoStore.set)
return memoStore
}