-
Notifications
You must be signed in to change notification settings - Fork 26
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c84a4c8
commit eb74156
Showing
2 changed files
with
31 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
import { LRUCache } from 'lru-cache'; | ||
|
||
const empty: unique symbol = Symbol('noValue'); | ||
|
||
// eslint-disable-next-line @typescript-eslint/ban-types | ||
export class Cache<K extends {}, V extends {}> { | ||
private cache: LRUCache<K, V | typeof empty>; | ||
|
||
public constructor(options: LRUCache.Options<K, V | typeof empty, unknown>) { | ||
this.cache = new LRUCache(options); | ||
} | ||
|
||
public get(key: K, calculate: () => V | undefined): V | undefined { | ||
if (this.cache.has(key)) { | ||
const cacheItem = this.cache.get(key); | ||
|
||
return cacheItem === empty ? undefined : cacheItem; | ||
} | ||
|
||
const calculated = calculate(); | ||
|
||
this.cache.set(key, calculated ?? empty); | ||
|
||
return calculated; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters