forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcacheUtils.ts
More file actions
93 lines (83 loc) · 2.42 KB
/
cacheUtils.ts
File metadata and controls
93 lines (83 loc) · 2.42 KB
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
const globalCacheStore = new Map<string, { expiry: number; data: any }>();
/**
* Gets a cache store to be used to store return values of methods or any other.
*
* @returns
*/
export function getGlobalCacheStore() {
return globalCacheStore;
}
export function getCacheKeyFromFunctionArgs(keyPrefix: string, fnArgs: any[]): string {
const argsKey = fnArgs.map((arg) => `${JSON.stringify(arg)}`).join('-Arg-Separator-');
return `KeyPrefix=${keyPrefix}-Args=${argsKey}`;
}
export function clearCache() {
globalCacheStore.clear();
}
type CacheData<T> = {
value: T;
expiry: number;
};
/**
* InMemoryCache caches a single value up until its expiry.
*/
export class InMemoryCache<T> {
private cacheData?: CacheData<T>;
constructor(protected readonly expiryDurationMs: number) {}
public get hasData() {
if (!this.cacheData || this.hasExpired(this.cacheData.expiry)) {
this.cacheData = undefined;
return false;
}
return true;
}
/**
* Returns undefined if there is no data.
* Uses `hasData` to determine whether any cached data exists.
*
* @readonly
* @type {(T | undefined)}
* @memberof InMemoryCache
*/
public get data(): T | undefined {
if (!this.hasData) {
return;
}
return this.cacheData?.value;
}
public set data(value: T | undefined) {
if (value !== undefined) {
this.cacheData = {
expiry: this.calculateExpiry(),
value,
};
} else {
this.cacheData = undefined;
}
}
public clear() {
this.cacheData = undefined;
}
/**
* Has this data expired?
* (protected class member to allow for reliable non-data-time-based testing)
*
* @param expiry The date to be tested for expiry.
* @returns true if the data expired, false otherwise.
*/
protected hasExpired(expiry: number): boolean {
return expiry <= Date.now();
}
/**
* When should this data item expire?
* (protected class method to allow for reliable non-data-time-based testing)
*
* @returns number representing the expiry time for this item.
*/
protected calculateExpiry(): number {
return Date.now() + this.expiryDurationMs;
}
}