File tree Expand file tree Collapse file tree 2 files changed +47
-2
lines changed
Expand file tree Collapse file tree 2 files changed +47
-2
lines changed Original file line number Diff line number Diff line change 1+ 'use strict' ;
2+
3+ // Facade for Map and Map or Timers
4+
5+ const TimeoutCollection = function ( timeout ) {
6+ this . timeout = timeout ;
7+ this . collection = new Map ( ) ;
8+ this . timers = new Map ( ) ;
9+ } ;
10+
11+ TimeoutCollection . prototype . set = function ( key , value ) {
12+ const timer = this . timers . get ( key ) ;
13+ if ( timer ) clearTimeout ( timer ) ;
14+ const timeout = setTimeout ( ( ) => {
15+ this . delete ( key ) ;
16+ } , this . timeout ) ;
17+ this . collection . set ( key , value ) ;
18+ this . timers . set ( key , timeout ) ;
19+ } ;
20+
21+ TimeoutCollection . prototype . get = function ( key ) {
22+ return this . collection . get ( key ) ;
23+ } ;
24+
25+ TimeoutCollection . prototype . delete = function ( key ) {
26+ const timer = this . timers . get ( key ) ;
27+ if ( timer ) {
28+ clearTimeout ( timer ) ;
29+ this . collection . delete ( key ) ;
30+ this . timers . delete ( key ) ;
31+ }
32+ } ;
33+
34+ TimeoutCollection . prototype . toArray = function ( ) {
35+ return [ ...this . collection . entries ( ) ] ;
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- # Facade
2- Pattern Facade Implementations
1+ # Pattern Facade Implementations
You can’t perform that action at this time.
0 commit comments