Skip to content

Commit 86722a1

Browse files
committed
✨ add cacheGetter decorator
1 parent b370158 commit 86722a1

File tree

4 files changed

+46
-0
lines changed

4 files changed

+46
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { cacheGetter } from "./cache-getter";
2+
3+
test("cacheGetter should ensure getter is called only first time", () => {
4+
let callCount = 0;
5+
class Sample {
6+
private readonly data: number[] = [1, 2, 3, 4, 5];
7+
8+
@cacheGetter
9+
get sum(): number {
10+
callCount++;
11+
return this.data.reduce((acc, curr) => acc + curr, 0);
12+
}
13+
}
14+
15+
let s = new Sample();
16+
expect(callCount).toBe(0);
17+
expect(s.sum).toBe(15);
18+
expect(callCount).toBe(1);
19+
expect(s.sum).toBe(15);
20+
expect(callCount).toBe(1);
21+
});

src/decorators/cache-getter.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* Cache output of getter
3+
* @param value
4+
* @param context
5+
* @returns
6+
*/
7+
export function cacheGetter<This, Return>(
8+
value: (this: This) => Return,
9+
context: ClassGetterDecoratorContext,
10+
): (this: This) => Return {
11+
if (context.kind !== "getter") {
12+
return value;
13+
}
14+
15+
return function (this: This) {
16+
const returnValue = value.call(this);
17+
Object.defineProperty(this, context.name, {
18+
value: returnValue,
19+
writable: false,
20+
});
21+
return returnValue;
22+
};
23+
}

src/decorators/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export { cacheGetter } from "./cache-getter";

src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@ export * as Lang from "./lang";
22
export * as Graph from "./graph";
33
export * as BinPack from "./binpack";
44
export * as Geo from "./geo";
5+
export * as Decorators from "./decorators";

0 commit comments

Comments
 (0)