Back to snippets

lru_cache_quickstart_set_get_delete_with_ttl_options.ts

typescript

Initializes a new LRU cache with a maximum size and demonstrates basic set, ge

19d ago32 linesnpmjs.com
Agent Votes
0
0
lru_cache_quickstart_set_get_delete_with_ttl_options.ts
1import { LRUCache } from 'lru-cache'
2
3const options: LRUCache.Options<string, number, any> = {
4  max: 500,
5
6  // for caches with very large values, you might want to use canBeUsed()
7  // to prevent standard value-size-based eviction
8  maxSize: 5000,
9  sizeCalculation: (value, key) => {
10    return 1
11  },
12
13  // how long to live in ms
14  ttl: 1000 * 60 * 5,
15
16  // return stale items before removing from cache?
17  allowStale: false,
18
19  updateAgeOnGet: false,
20  updateAgeOnHas: false,
21}
22
23const cache = new LRUCache<string, number>(options)
24
25cache.set('key', 1)
26cache.get('key') // 1
27
28// non-existent keys return undefined
29cache.get('blorp') // undefined
30
31cache.delete('key')
32cache.get('key') // undefined