Created
February 9, 2017 16:29
-
-
Save unstoppablecarl/1fb9c466c073bb580a85388219d1bd3b to your computer and use it in GitHub Desktop.
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 NOT_FOUND = 'NOT_FOUND'; | |
const cache = {}; | |
const db = [ | |
{ | |
id: 1, | |
name: 'steve', | |
email: '[email protected]' | |
}, | |
{ | |
id: 2, | |
name: 'bobby', | |
email: '[email protected]' | |
} | |
]; | |
function fetchData(id) { | |
console.log('--- FETCH FROM DB ---', id); | |
var item = db[id]; | |
if (item === undefined) { | |
return NOT_FOUND; | |
} | |
return item; | |
} | |
function get(id, prop, forceRefresh = false) { | |
var item = cache[id]; | |
if (forceRefresh || item === undefined) { | |
item = cache[id] = fetchData(id); | |
} else { | |
console.log('--- FETCH FROM CACHE ---', id) | |
} | |
if (item === NOT_FOUND) { | |
return NOT_FOUND; | |
} | |
if (item) { | |
return item[prop]; | |
} | |
} | |
console.log('cache (empty)', cache); | |
console.log('db miss', get(3, 'name')); | |
console.log('db miss (cached)', get(3, 'name')); | |
console.log('1.name', get(1, 'name')); | |
console.log('1.email', get(1, 'email')); | |
console.log('cache (primed)', cache); | |
console.log('2.email', get(2, 'email')); | |
console.log('2.email (forceRefresh)', get(2, 'email', true)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment