Skip to content

Instantly share code, notes, and snippets.

@zz85
Created July 8, 2017 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zz85/906f4f47c31525062000f87d08b9cdce to your computer and use it in GitHub Desktop.
Save zz85/906f4f47c31525062000f87d08b9cdce to your computer and use it in GitHub Desktop.
Generic Cache
class GenericCache {
constructor() {
this.cache = new Map();
}
set(key, promise, options) {
if (typeof promise === 'function') {
promise = promise();
}
this.cache.set(key, promise);
return promise;
}
has(key) {
return this.cache.has(key);
}
get(key) {
return this.cache.get(key);
}
getSet(key, expression, options) {
if (this.has(key)) {
return this.cache.get(key);
}
if (expression) {
return this.set(key, expression, options);
}
// return Promise.reject({ reason: 'no key' });
}
delete(key) {
this.cache.delete(key);
}
}
const cache = new GenericCache();
cache.set(1, Promise.resolve('1'));
cache.get(1).then(v => console.log('get 1', v));
cache.set(2, () => {
return Promise.resolve(2);
});
cache.get(2).then(v => console.log('get 2', v));
delay = (t) => new Promise(a => {setTimeout(a, t * 1000, t)});
cache.set(3, () => {
return delay(3);
});
cache.get(3).then(v => console.log('get 3', v))
.then(() => {
cache.get(3).then(v => console.log('get 3 again', v));
});
delay(2).then(v => {
cache.delete(1);
console.log('after delete', cache.get(1));
})
cache.getSet(4, () => {
return delay(4);
}).then(v => console.log('get 4', v))
.then(() => {
cache.get(4).then(v => console.log('get 4 again', v));
});

Implement generic cache similar to the spray-caching and cache pattern used by StackOverflow

cache.getSet(key, expensiveExpression).then()
// set if key is null / not existent.

cache.set(key, < promise expression >, < cache options >)

cache.get(key).then()

cache.delete()

Cache can be off an LRU + Expiring nature.

Examples

// Caching multiple inflight requests
cache.getSet('fetch.${something}', () => fetch('blabla')).then()

// Using getSet as a lock
cache.getSet(`processed.${mid}`, () => {
  processMessage();
  cache.del()
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment