Created
January 18, 2021 14:29
-
-
Save kozo002/14484511ce583bf335b3bcc96ce80f57 to your computer and use it in GitHub Desktop.
memoizeSelector
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
const memoizeSelector = (getDeps, selector) => { | |
const lastDeps = [] | |
let lastResult | |
return (store) => { | |
let updated = false | |
const deps = getDeps.map((getDep, i) => { | |
const dep = getDep(store) | |
if (dep !== lastDeps[i]) { | |
lastDeps[i] = dep | |
updated = true | |
} | |
return dep | |
}) | |
if (updated) { | |
lastResult = selector(store, ...deps) | |
} | |
return lastResult | |
} | |
} | |
const selector = memoizeSelector([ | |
(store) => store.items | |
], (store, items) => { | |
return items.map((it) => it.id).join()+store.other | |
}) | |
const store = { | |
items: [ | |
{ id: 1 }, | |
{ id: 2 }, | |
{ id: 3 }, | |
], | |
other: 'this is the other prop' | |
} | |
console.log(selector(store)) | |
store.items[0].id = 0 | |
console.log(selector(store)) | |
store.items = [...store.items, { id: 4 }] | |
console.log(selector(store)) | |
store.other = 'foo bar' | |
console.log(selector(store)) | |
store.items = [...store.items] | |
console.log(selector(store)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment