Created
September 3, 2019 08:35
-
-
Save yarastqt/8af64e8f3cf937455865f5ef195adaa6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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