Commit 3c07bce 1 parent 2f7a039 commit 3c07bce Copy full SHA for 3c07bce
File tree 3 files changed +62
-0
lines changed
3 files changed +62
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Cache class which allows to store Key-Value pairs with a TTL for each key
3
+ */
4
+ export class Cache {
5
+ store : Map < string , { value : any ; ttl : number } > ;
6
+
7
+ constructor ( ) {
8
+ this . store = new Map ( ) ;
9
+ }
10
+
11
+ set ( key : string , value : any , ttl : number ) {
12
+ this . store . set ( key , { value, ttl : Date . now ( ) + ttl } ) ;
13
+ }
14
+
15
+ get ( key : string ) {
16
+ const entry = this . store . get ( key ) ;
17
+ if ( ! entry ) return ;
18
+ if ( entry . ttl < Date . now ( ) ) {
19
+ this . store . delete ( key ) ;
20
+
21
+ return ;
22
+ }
23
+
24
+ return entry . value ;
25
+ }
26
+
27
+ delete ( key : string ) {
28
+ this . store . delete ( key ) ;
29
+ }
30
+ }
Original file line number Diff line number Diff line change @@ -8,6 +8,7 @@ export * from './arrayPartition';
8
8
export * from './arrayShuffle' ;
9
9
export * from './arrayToDictionary' ;
10
10
export * from './bytesToHumanReadable' ;
11
+ export * from './cache' ;
11
12
export * from './capitalizeFirstLetter' ;
12
13
export * from './cloneObject' ;
13
14
export * from './countBytesInString' ;
Original file line number Diff line number Diff line change
1
+ import { Cache } from '../src/cache' ;
2
+
3
+ const delay = ( ms : number ) => jest . advanceTimersByTime ( ms ) ;
4
+
5
+ const TTL = 100 ;
6
+
7
+ describe ( 'Cache' , ( ) => {
8
+ let cache : Cache ;
9
+
10
+ beforeEach ( ( ) => {
11
+ jest . useFakeTimers ( ) ;
12
+ cache = new Cache ( ) ;
13
+ } ) ;
14
+
15
+ it ( 'set and get' , ( ) => {
16
+ cache . set ( 'key' , 'value' , TTL ) ;
17
+ expect ( cache . get ( 'key' ) ) . toEqual ( 'value' ) ;
18
+ } ) ;
19
+
20
+ it ( 'get with expired TTL' , ( ) => {
21
+ cache . set ( 'key' , 'value' , TTL ) ;
22
+ delay ( TTL + 1 ) ;
23
+ expect ( cache . get ( 'key' ) ) . toBeUndefined ( ) ;
24
+ } ) ;
25
+
26
+ it ( 'delete' , ( ) => {
27
+ cache . set ( 'key' , 'value' , TTL ) ;
28
+ cache . delete ( 'key' ) ;
29
+ expect ( cache . get ( 'key' ) ) . toBeUndefined ( ) ;
30
+ } ) ;
31
+ } ) ;
You can’t perform that action at this time.
0 commit comments