Skip to content

Instantly share code, notes, and snippets.

@gilbox
Last active October 18, 2015 21:17
Show Gist options
  • Save gilbox/30140dd4854ca31e5074 to your computer and use it in GitHub Desktop.
Save gilbox/30140dd4854ca31e5074 to your computer and use it in GitHub Desktop.
cacheMap
// 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