blob: 1e675c36e43b7713f6babda4d7f06284b48b1b2e (
plain)
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
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
import { IDisposable } from 'vs/base/common/lifecycle';
export interface CacheResult<T> extends IDisposable {
promise: Promise<T>;
}
export class Cache<T> {
private result: CacheResult<T> | null = null;
constructor(private task: (ct: CancellationToken) => Promise<T>) { }
get(): CacheResult<T> {
if (this.result) {
return this.result;
}
const cts = new CancellationTokenSource();
const promise = this.task(cts.token);
this.result = {
promise,
dispose: () => {
this.result = null;
cts.cancel();
cts.dispose();
}
};
return this.result;
}
}
/**
* Uses a LRU cache to make a given parametrized function cached.
* Caches just the last value.
* The key must be JSON serializable.
*/
export class LRUCachedFunction<TArg, TComputed> {
private lastCache: TComputed | undefined = undefined;
private lastArgKey: string | undefined = undefined;
constructor(private readonly fn: (arg: TArg) => TComputed) {
}
public get(arg: TArg): TComputed {
const key = JSON.stringify(arg);
if (this.lastArgKey !== key) {
this.lastArgKey = key;
this.lastCache = this.fn(arg);
}
return this.lastCache!;
}
}
/**
* Uses an unbounded cache (referential equality) to memoize the results of the given function.
*/
export class CachedFunction<TArg, TValue> {
private readonly _map = new Map<TArg, TValue>();
public get cachedValues(): ReadonlyMap<TArg, TValue> {
return this._map;
}
constructor(private readonly fn: (arg: TArg) => TValue) { }
public get(arg: TArg): TValue {
if (this._map.has(arg)) {
return this._map.get(arg)!;
}
const value = this.fn(arg);
this._map.set(arg, value);
return value;
}
}
|