Created
October 12, 2022 12:10
-
-
Save ksimons/3c05c9c466bac1e3d1a9b9af742bee3b to your computer and use it in GitHub Desktop.
Recoil.js selector family that allows for equality checking
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
function equalSelectorFamily<T, P extends SerializableParam>( | |
options: EqualSelectorFamilyOptions<T, P> | |
) { | |
const inner = selectorFamily<T, P>({ | |
key: `${options.key}_inner`, | |
get: options.get, | |
}); | |
const priorValues: Map<P, T | undefined> = new Map(); | |
return selectorFamily<T, P>({ | |
...options, | |
key: options.key, | |
get: | |
(param: P) => | |
({ get }) => { | |
const latest = get(inner(param)); | |
const prior = priorValues.get(param); | |
if (prior != null && options.equals(latest, prior)) { | |
return prior; | |
} | |
priorValues.set(param, latest); | |
return latest; | |
}, | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment