Skip to content

Commit 066b736

Browse files
authored
Merge pull request #1 from adamjosefus/development
Create `Cache` class.
2 parents df4da57 + c75d0dd commit 066b736

File tree

4 files changed

+56
-0
lines changed

4 files changed

+56
-0
lines changed

Diff for: .gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
.DS_Store
2+
!.vscode/settings.json

Diff for: .vscode/settings.json

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"deno.enable": true,
3+
"deno.lint": true,
4+
"deno.unstable": false
5+
}

Diff for: Cache/Cache.ts

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* @copyright Copyright (c) 2022 Adam Josefus
3+
*/
4+
5+
type GeneratorType<T> = () => T;
6+
7+
type LoadOnlyEntryType<T> = [key: string];
8+
type LoadAndGenerateEntryType<T> = [key: string, generator: GeneratorType<T>];
9+
type LoadEntryType<T> = LoadOnlyEntryType<T> | LoadAndGenerateEntryType<T>;
10+
11+
12+
export class Cache<T> {
13+
14+
readonly #storage: Map<string, T> = new Map();
15+
16+
load<E extends LoadEntryType<T>>(...args: E): E extends LoadAndGenerateEntryType<T> ? T : T | undefined {
17+
const [key, generator] = args;
18+
19+
if (this.#storage.has(key)) {
20+
return this.#storage.get(key)!;
21+
}
22+
23+
if (generator) {
24+
const value = generator();
25+
this.save(key, value);
26+
27+
return value;
28+
}
29+
30+
// deno-lint-ignore no-explicit-any
31+
return undefined as any;
32+
}
33+
34+
35+
save(key: string, value: T): void {
36+
this.#storage.set(key, value);
37+
}
38+
39+
40+
has(key: string): boolean {
41+
return this.#storage.has(key);
42+
}
43+
44+
45+
delete(key: string): void {
46+
this.#storage.delete(key);
47+
}
48+
}

Diff for: mod.ts

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export { Cache } from './Cache/Cache.ts';

0 commit comments

Comments
 (0)