-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cache.ts
116 lines (86 loc) · 2.48 KB
/
cache.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import type {SerialiserFn} from './core';
type Fn<T, A extends any[], R> = (this: T, ...args: A) => R;
/** @see {MEMOISE_CACHE_TYPED} */
export interface Cache<K = any, A extends any[] = any[]> {
/** Clear the cache */
clear(): void;
/**
* Delete a specific cache entry.
* @param key The result of passing the method call args through the associated {@link SerialiserFn serialiser fn}
*/
delete(key: K): boolean;
/** Like {@link Cache#delete}, but the key gets computed */
deleteWithArgs(...args: A): boolean;
/**
* Check if a specific cache entry exists.
* @param key See {@link Cache#delete delete()}
*/
has(key: K): boolean;
/** Like {@link Cache#has}, but the key gets computed */
hasWithArgs(...args: A): boolean;
}
/** @internal */
export class ArglessCtx<T, R> implements Cache<any, []> {
private readonly _ctx: T;
private _firstCall = true;
private readonly _orig: Fn<T, [], R>;
private _value?: R;
public constructor(ctx: T, origFn: Fn<T, [], R>) {
this._orig = origFn;
this._ctx = ctx;
}
public autoGet(): R {
if (this._firstCall) {
this._value = this._orig.call(this._ctx);
this._firstCall = false;
}
return this._value!;
}
public clear(): void {
this._firstCall = true;
}
public delete(): boolean {
const ret = this.has();
this.clear();
return ret;
}
public deleteWithArgs(): boolean {
return this.delete();
}
public has(): boolean {
return !this._firstCall;
}
public hasWithArgs(): boolean {
return this.has();
}
}
/** @internal */
export class ArgedCtx<T, A extends any[], R, K> extends Map<K, R> implements Cache<K, A> {
private readonly _ctx: T;
private readonly _orig: Fn<T, A, R>;
private readonly _serialiser: SerialiserFn<T, A, K>;
public constructor(ctx: T, origFn: Fn<T, A, R>, serialiser: SerialiserFn<T, A, K>) {
super();
this._ctx = ctx;
this._orig = origFn;
this._serialiser = serialiser;
}
public autoGet(args: A | IArguments): R {
const key = this.keyFor(args);
if (this.has(key)) {
return this.get(key)!;
}
const value = this._orig.apply(this._ctx, args as A);
this.set(key, value);
return value;
}
public deleteWithArgs(...args: A): boolean {
return this.delete(this.keyFor(args));
}
public hasWithArgs(...args: A): boolean {
return this.has(this.keyFor(args));
}
private keyFor(args: A | IArguments): K {
return this._serialiser.apply(this._ctx, args as A);
}
}