forked from aptos-labs/aptos-ts-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemoize.ts
68 lines (59 loc) · 2.02 KB
/
memoize.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
// Copyright © Aptos Foundation
// SPDX-License-Identifier: Apache-2.0
/**
* The global cache Map shared across all functions. Must keep care to ensure that the
* cache keys are unique across all functions.
*/
const cache = new Map<string, { value: any; timestamp: number }>();
/**
* A memoize high order function to cache async function response
*
* @param func An async function to cache the result of
* @param key The provided cache key
* @param ttlMs time-to-live in milliseconds for cached data
* @returns the cached or latest result
*/
export function memoizeAsync<T>(
func: (...args: any[]) => Promise<T>,
key: string,
ttlMs?: number,
): (...args: any[]) => Promise<T> {
return async (...args: any[]) => {
// Check if the cached result exists and is within TTL
if (cache.has(key)) {
const { value, timestamp } = cache.get(key)!;
if (ttlMs === undefined || Date.now() - timestamp <= ttlMs) {
return value;
}
}
// If not cached or TTL expired, compute the result
const result = await func(...args);
// Cache the result with a timestamp
cache.set(key, { value: result, timestamp: Date.now() });
return result;
};
}
/**
* A memoize high order function to cache function response
*
* @param func A function to cache the result of
* @param key The provided cache key
* @param ttlMs time-to-live in milliseconds for cached data
* @returns the cached or latest result
*/
export function memoize<T>(func: (...args: any[]) => T, key: string, ttlMs?: number): (...args: any[]) => T {
return (...args: any[]) => {
// Check if the cached result exists and is within TTL
if (cache.has(key)) {
const { value, timestamp } = cache.get(key)!;
if (ttlMs === undefined || Date.now() - timestamp <= ttlMs) {
return value;
}
}
// If not cached or TTL expired, compute the result
const result = func(...args);
// Cache the result with a timestamp
cache.set(key, { value: result, timestamp: Date.now() });
return result;
};
}