Skip to content

Instantly share code, notes, and snippets.

@yarastqt
Created September 3, 2019 08:35
Show Gist options
  • Save yarastqt/8af64e8f3cf937455865f5ef195adaa6 to your computer and use it in GitHub Desktop.
Save yarastqt/8af64e8f3cf937455865f5ef195adaa6 to your computer and use it in GitHub Desktop.
const createCache = () => {
const cacheMap = new Map()
return {
remember(key, setter) {
if (this.has(key)) {
return this.get(key)
}
const value = setter.call(null)
this.set(key, value)
return value
},
has(key) {
return cacheMap.has(key)
},
set(key, value) {
cacheMap.set(key, value)
},
get(key) {
return cacheMap.get(key)
},
}
}
const cache = createCache()
let result1 = null
if (cache.has('post')) {
result1 = cache.get('post')
} else {
result1 = { id: 1 }
cache.set('post', result1)
}
const result2 = cache.remember('post', () => ({ id: 1 }))
console.log(result1)
console.log(result2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment