@zelgadis87/utils-core 5.0.0 → 5.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lazy/LazyDictionary.d.ts +9 -0
- package/dist/lazy/_index.d.ts +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/esbuild/index.cjs +27 -0
- package/esbuild/index.cjs.map +3 -3
- package/esbuild/index.mjs +26 -0
- package/esbuild/index.mjs.map +3 -3
- package/package.json +1 -1
- package/src/lazy/LazyDictionary.ts +33 -0
- package/src/lazy/_index.ts +2 -0
package/package.json
CHANGED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { TFunction } from "../utils/_index.ts";
|
|
2
|
+
|
|
3
|
+
export class LazyDictionary<K extends string | number | symbol, T> {
|
|
4
|
+
|
|
5
|
+
private readonly _dictionary: Partial<Record<K, T>> = {};
|
|
6
|
+
|
|
7
|
+
private constructor(
|
|
8
|
+
private readonly _generator: TFunction<K, T>
|
|
9
|
+
) { }
|
|
10
|
+
|
|
11
|
+
public static of<K extends string | number | symbol, T>( generator: TFunction<K, T> ) {
|
|
12
|
+
return new LazyDictionary<K, T>( generator );
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
public getOrCreate( key: K ): T {
|
|
16
|
+
if ( key in this._dictionary ) {
|
|
17
|
+
return this._dictionary[ key ] as T;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const value = this._generator( key );
|
|
21
|
+
this._dictionary[ key ] = value;
|
|
22
|
+
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
public getOrThrow( key: K , errorMessage?: "Value not initialized" ): T {
|
|
27
|
+
if ( key in this._dictionary ) {
|
|
28
|
+
return this._dictionary[ key ] as T;
|
|
29
|
+
}
|
|
30
|
+
throw new Error( errorMessage );
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
}
|