Skip to content

Instantly share code, notes, and snippets.

@renatoargh
Created September 6, 2019 12:29
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 renatoargh/36f1a325962fe8b63bf73e409d56716b to your computer and use it in GitHub Desktop.
Save renatoargh/36f1a325962fe8b63bf73e409d56716b to your computer and use it in GitHub Desktop.
interface ObjectInterface {
[key: string]: any;
}
function initCache<T>(obj: any): T {
const cache = {};
return new Proxy(obj, {
get(target: ObjectInterface, methodKey: string) {
const originalMethod = target[methodKey];
return (...args: any) => {
const key: string = args.join(':');
if (cache[key]) {
return cache[key];
}
cache[key] = originalMethod.apply(obj, args);
return cache[key];
};
},
});
}
interface CarRepoInterface {
getCars(): Promise<string[]>;
}
class CarRepo implements CarRepoInterface {
private allCars = ['bmw', 'ferrari'];
getCars(): Promise<string[]> {
return new Promise(resolve =>
setTimeout(() => {
resolve(this.allCars);
}, 3000),
);
}
}
async function main() {
const carRepo = new CarRepo();
console.log('> No cache');
for (let i = 0; i < 3; i++) {
console.time('timing');
await carRepo.getCars();
console.timeEnd('timing');
}
console.log();
console.log('----------');
console.log();
const cachedCarRepo: CarRepoInterface = initCache<CarRepoInterface>(carRepo);
console.log('> With Cache');
for (let i = 0; i < 3; i++) {
console.time('timing');
await cachedCarRepo.getCars();
console.timeEnd('timing');
}
}
main();
const myObject = { getCars: () => new Promise() };
const asd: CarRepoInterface = new Proxy(myObject, {});
console.log(asd);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment