File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ 'use strict' ;
2+
3+ class TimeoutCollection {
4+ constructor ( timeout ) {
5+ this . timeout = timeout ;
6+ this . collection = new Map ( ) ;
7+ this . timers = new Map ( ) ;
8+ }
9+
10+ set ( key , value ) {
11+ const timer = this . timers . get ( key ) ;
12+ if ( timer ) clearTimeout ( timer ) ;
13+ const timeout = setTimeout ( ( ) => {
14+ this . delete ( key ) ;
15+ } , this . timeout ) ;
16+ this . collection . set ( key , value ) ;
17+ this . timers . set ( key , timeout ) ;
18+ }
19+
20+ get ( key ) {
21+ return this . collection . get ( key ) ;
22+ }
23+
24+ delete ( key ) {
25+ const timer = this . timers . get ( key ) ;
26+ if ( timer ) {
27+ clearTimeout ( timer ) ;
28+ this . collection . delete ( key ) ;
29+ this . timers . delete ( key ) ;
30+ }
31+ }
32+
33+ toArray ( ) {
34+ return [ ...this . collection . entries ( ) ] ;
35+ }
36+ }
37+
38+ // Usage
39+
40+ const hash = new TimeoutCollection ( 1000 ) ;
41+ hash . set ( 'uno' , 1 ) ;
42+ setTimeout ( ( ) => {
43+ hash . set ( 'due' , 2 ) ;
44+ hash . set ( 'tre' , 3 ) ;
45+ console . dir ( { array : hash . toArray ( ) } ) ;
46+ } , 1500 ) ;
Original file line number Diff line number Diff line change 1+ 'use strict' ;
2+
3+ const timeoutCollection = timeout => {
4+ const collection = new Map ( ) ;
5+ const timers = new Map ( ) ;
6+ const facade = { } ;
7+
8+ facade . set = ( key , value ) => {
9+ const prevTimer = timers . get ( key ) ;
10+ if ( prevTimer ) clearTimeout ( prevTimer ) ;
11+ const timer = setTimeout ( ( ) => {
12+ collection . delete ( key ) ;
13+ } , timeout ) ;
14+ collection . set ( key , value ) ;
15+ timers . set ( key , timer ) ;
16+ } ;
17+
18+ facade . get = key => collection . get ( key ) ;
19+
20+ facade . delete = key => {
21+ const timer = timers . get ( key ) ;
22+ if ( timer ) {
23+ clearTimeout ( timer ) ;
24+ collection . delete ( key ) ;
25+ timers . delete ( key ) ;
26+ }
27+ } ;
28+
29+ facade . toArray = ( ) => [ ...collection . entries ( ) ] ;
30+
31+ return facade ;
32+ } ;
33+
34+ // Usage
35+
36+ const hash = timeoutCollection ( 1000 ) ;
37+ hash . set ( 'uno' , 1 ) ;
38+ setTimeout ( ( ) => {
39+ hash . set ( 'due' , 2 ) ;
40+ hash . set ( 'tre' , 3 ) ;
41+ console . dir ( { array : hash . toArray ( ) } ) ;
42+ } , 1500 ) ;
You can’t perform that action at this time.
0 commit comments