-
Notifications
You must be signed in to change notification settings - Fork 65
/
lmr-cache.js
57 lines (52 loc) · 1.35 KB
/
lmr-cache.js
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
/**
* Provides {@link LMRCache}
*
* @packageDescription
*/
import { LavamoatModuleRecord } from 'lavamoat-core'
/**
* This class represents a transient cache for
* {@link LavamoatModuleRecord LavamoatModuleRecords}.
*
* It's a thin wrapper around a `Map`; it's used to ensure we don't create
* duplicate `LavamoatModuleRecord` objects for the same specifiers.
*/
export class LMRCache {
/** @type {Map<string, LavamoatModuleRecord>} */
#cache
constructor() {
this.#cache = new Map()
}
/**
* Computes the cache key for a given {@link LavamoatModuleRecord} or its
* options.
*
* @param {import('lavamoat-core').LavamoatModuleRecordOptions
* | LavamoatModuleRecord} opts
* @returns {string}
* @todo Determine if this is appropriately unique
*/
static keyFor({ specifier, file }) {
return `${specifier}:${file}`
}
/**
* Gets or creates a new {@link LavamoatModuleRecord} for the given options.
*
* @param {import('lavamoat-core').LavamoatModuleRecordOptions} opts
*/
get(opts) {
const key = LMRCache.keyFor(opts)
if (this.#cache.has(key)) {
return /** @type {LavamoatModuleRecord} */ (this.#cache.get(key))
}
const record = new LavamoatModuleRecord(opts)
this.#cache.set(key, record)
return record
}
/**
* Clears the cache
*/
clear() {
this.#cache.clear()
}
}