UNPKG

813 BPlain TextView Raw
1import { MemoCache } from '@naturalcycles/js-lib'
2import * as LRUCache from 'lru-cache'
3
4// Partial, to be able to provide default `max`
5export type LRUMemoCacheOptions<KEY, VALUE> = Partial<LRUCache.Options<KEY, VALUE>>
6
7/**
8 * @example
9 * Use it like this:
10 *
11 * @_Memo({ cacheFactory: () => new LRUMemoCache({...}) })
12 * method1 ()
13 */
14export class LRUMemoCache<KEY = any, VALUE = any> implements MemoCache<KEY, VALUE> {
15 constructor(opt: LRUMemoCacheOptions<KEY, VALUE>) {
16 this.lru = new LRUCache<KEY, VALUE>({
17 max: 100,
18 ...opt,
19 })
20 }
21
22 private lru!: LRUCache<KEY, VALUE>
23
24 has(k: any): boolean {
25 return this.lru.has(k)
26 }
27
28 get(k: any): any {
29 return this.lru.get(k)
30 }
31
32 set(k: any, v: any): void {
33 this.lru.set(k, v)
34 }
35
36 clear(): void {
37 this.lru.clear()
38 }
39}