-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
chore: create svelte store to deep compare values
Update the store value if previous and new values aren't deep equal
- Loading branch information
1 parent
7fd5e30
commit b3cf1f3
Showing
2 changed files
with
39 additions
and
38 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
import { writable, get } from 'svelte/store'; | ||
|
||
/** | ||
* Creates a Svelte writable store that compares values deeply before updating. | ||
* | ||
* @param initialValue - The initial value for the store. | ||
* @returns An object containing the subscribe and set methods. | ||
*/ | ||
const createDeepEqual = <V>(initialValue: V | undefined) => { | ||
const value = writable<V | undefined>(initialValue); | ||
|
||
return { | ||
/** | ||
* Subscribes to changes in the store's value. | ||
*/ | ||
subscribe: value.subscribe, | ||
/** | ||
* Sets the new value for the store if it differs from the current value | ||
* by performing a deep comparison. | ||
*/ | ||
set: (newValue: V | undefined) => { | ||
if (JSON.stringify(newValue) !== JSON.stringify(get(value))) { | ||
value.set(newValue); | ||
} | ||
}, | ||
}; | ||
}; | ||
|
||
export default createDeepEqual; |