@@ -25,26 +25,44 @@ class Dictionary {
25
25
clear ( ) {
26
26
this . map = Object . create ( null ) ;
27
27
}
28
+ static from ( hash ) {
29
+ const instance = new Dictionary ( ) ;
30
+ for ( const key in hash ) {
31
+ instance . set ( key , hash [ key ] ) ;
32
+ }
33
+ return instance ;
34
+ }
28
35
}
29
36
30
37
// Usage
31
38
32
- const cityPopulation = new Dictionary ( ) ;
39
+ const cities = {
40
+ Shanghai : 24256800 ,
41
+ Beijing : 21516000 ,
42
+ Delhi : 16787941 ,
43
+ Lagos : 16060303
44
+ } ;
45
+
46
+ const cityPopulation1 = Dictionary . from ( cities ) ;
47
+ console . dir ( { cityPopulation1 } ) ;
33
48
34
- cityPopulation . set ( 'Shanghai' , 24256800 ) ;
35
- cityPopulation . set ( 'Beijing' , 21516000 ) ;
36
- cityPopulation . set ( 'Delhi' , 16787941 ) ;
37
- cityPopulation . set ( 'Lagos' , 16060303 ) ;
49
+ const cityPopulation2 = new Dictionary ( ) ;
50
+ cityPopulation2 . set ( 'Shanghai' , 24256800 ) ;
51
+ cityPopulation2 . set ( 'Beijing' , 21516000 ) ;
52
+ cityPopulation2 . set ( 'Delhi' , 16787941 ) ;
53
+ cityPopulation2 . set ( 'Lagos' , 16060303 ) ;
54
+ console . dir ( { cityPopulation2 } ) ;
38
55
39
- cityPopulation . delete ( 'Shanghai' ) ;
56
+ cityPopulation2 . delete ( 'Shanghai' ) ;
57
+ console . dir ( { cityPopulation2 } ) ;
40
58
41
- if ( cityPopulation . has ( 'Beijing' ) ) {
42
- console . log ( 'Beijing:' , cityPopulation . get ( 'Beijing' ) ) ;
59
+ if ( cityPopulation2 . has ( 'Beijing' ) ) {
60
+ console . log ( 'Beijing:' , cityPopulation2 . get ( 'Beijing' ) ) ;
43
61
}
44
62
45
- if ( ! cityPopulation . has ( 'Shanghai' ) ) {
63
+ if ( ! cityPopulation2 . has ( 'Shanghai' ) ) {
46
64
console . log ( 'no data for Shanghai' ) ;
47
65
}
48
66
49
- console . log ( 'size:' , cityPopulation . size ) ;
50
- console . log ( 'keys:' , cityPopulation . keys ( ) ) ;
67
+ console . log ( 'size:' , cityPopulation2 . size ) ;
68
+ console . log ( 'keys:' , cityPopulation2 . keys ( ) ) ;
0 commit comments