Created
September 6, 2019 12:29
-
-
Save renatoargh/36f1a325962fe8b63bf73e409d56716b to your computer and use it in GitHub Desktop.
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
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