Skip to content

Instantly share code, notes, and snippets.

@k1r0s
Created December 6, 2017 23:35
Show Gist options
  • Select an option

  • Save k1r0s/1b07dbf6c5f37df7248e2f5f0b174a80 to your computer and use it in GitHub Desktop.

Select an option

Save k1r0s/1b07dbf6c5f37df7248e2f5f0b174a80 to your computer and use it in GitHub Desktop.
kaop-ts caching advice showcase `memoization`
import { beforeMethod, afterMethod } from "..";
const methodSpy = jest.fn();
const Delay = secs => meta => setTimeout(meta.commit, secs);
const Cache = (function() {
const CACHE_KEY = "#CACHE";
return {
read: meta => {
if(!meta.scope[CACHE_KEY]) meta.scope[CACHE_KEY] = {};
if(meta.scope[CACHE_KEY][meta.key]) {
meta.result = meta.scope[CACHE_KEY][meta.key];
meta.break();
}
},
write: meta => {
meta.scope[CACHE_KEY][meta.key] = meta.result;
}
}
})();
class Person {
name
age
constructor(name, yearBorn) {
this.name = name;
this.age = new Date(yearBorn, 1, 1);
}
@beforeMethod(Cache.read)
@afterMethod(Cache.write)
_veryHeavyCalculation() {
methodSpy();
const today = new Date();
return today.getFullYear() - this.age.getFullYear();
}
sayHello(){
return `hello, I'm ${this.name}, and I'm ${this._veryHeavyCalculation()} years old`;
}
@beforeMethod(Delay(300))
doSomething(cbk) {
cbk();
}
}
let personInstance;
describe("advance reflect.advice specs", () => {
beforeAll(() => {
personInstance = new Person("Manuelo", 1998);
})
it("cache advices should avoid '_veryHeavyCalculation' to be called more than once", () => {
personInstance.sayHello();
personInstance.sayHello();
personInstance.sayHello();
expect(methodSpy).toHaveBeenCalledTimes(1)
})
it("Delay advice should stop the execution for at least one segond", done => {
const time = Date.now();
personInstance.doSomething(function() {
expect(Date.now() - time).toBeGreaterThan(280);
done();
});
});
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment