Skip to content

Instantly share code, notes, and snippets.

@kozo002
Created January 18, 2021 14:29
Show Gist options
  • Save kozo002/14484511ce583bf335b3bcc96ce80f57 to your computer and use it in GitHub Desktop.
Save kozo002/14484511ce583bf335b3bcc96ce80f57 to your computer and use it in GitHub Desktop.
memoizeSelector
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