Last active
October 18, 2015 21:17
-
-
Save gilbox/30140dd4854ca31e5074 to your computer and use it in GitHub Desktop.
cacheMap
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
// cache an immutable list | |
// Ie: if an item changes, it's cacheKey *must* change as well | |
const cache = {}; | |
function cacheMap(objectKey, mapFn) { | |
const objectCache = cache[objectKey] || {}; | |
const nextObjectCache = cache[objectKey] = {}; | |
return this.map(item => | |
nextObjectCache[item.cacheKey] = | |
objectCache[item.cacheKey] || mapFn(item) | |
); | |
} | |
// example: | |
const list = [{ val: 'foo', cacheKey: 'foo'}, { val: 'bar', cacheKey: 'bar'}]; | |
const doIt = () => list::cacheMap('list', ({val, cacheKey}) => { | |
console.log('evaluate ', cacheKey); | |
return `(${val})`; | |
}).join(','); | |
console.log(doIt()); | |
//=> evaluate foo | |
//=> evaluate bar | |
//=> (foo),(bar) | |
list.push({ val: 'ack', cacheKey: 'ack' }); | |
console.log(doIt()); | |
//=> evaluate ack | |
//=> (foo),(bar),(ack) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment