Skip to content

Instantly share code, notes, and snippets.

@k10526
Created April 10, 2020 07:03
Show Gist options
  • Save k10526/2c64d00d73c82c8e52c40bb98db0bb74 to your computer and use it in GitHub Desktop.
Save k10526/2c64d00d73c82c8e52c40bb98db0bb74 to your computer and use it in GitHub Desktop.
/**
* @template T1
*/
class CacheChain {
/**
* @param {function():*|function():CacheChain<*>} fn
*/
constructor(fn) {
this._fn = fn;
this._cache = null;
}
/**
* @template T1
* @template T2
* @param {function(T1):T2|function(T1):CacheChain<T2>}fn
* @return {CacheChain<T2>}
*/
then(fn) {
if (!this._cache) {
this._cache = this._fn();
}
if (this._cache instanceof CacheChain) {
return this._cache.then(fn);
} else {
Object.freeze(this._cache);
return new CacheChain(() => fn(this._cache));
}
}
/**
* @deprecated
* @return {T1}
*/
get value() {
let res = null;
this.then((data) => {
res = data;
}).then(_ => _);
return res;
}
}
export default CacheChain;
// @desc
// const c = new CacheChain(() => ({a:1, b:2}));
// const cc1 = c.then((obj) => {console.log(obj); return obj?.a});
// const cc2 = c.then((obj) => {console.log(obj); return obj?.b});
// cc1.then((a) => console.log(a));
// cc2.then((b) => console.log(b));
//
// result
// c cache
// cc1 cache {a:1, b:2}
// cc2 cache {a:1, b:2}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment