File tree Expand file tree Collapse file tree 2 files changed +56
-2
lines changed
Expand file tree Collapse file tree 2 files changed +56
-2
lines changed Original file line number Diff line number Diff line change 1+ 'use strict' ;
2+
3+ // Interface adapter: fs to Map
4+
5+ class HashMap {
6+ constructor ( fs , path ) {
7+ this . fs = fs ;
8+ this . path = path ;
9+ fs . mkdirSync ( path ) ;
10+ }
11+ set ( key , value ) {
12+ this . fs . writeFileSync ( this . path + key , JSON . stringify ( value ) , 'utf8' ) ;
13+ }
14+ get ( key ) {
15+ return JSON . parse ( this . fs . readFileSync ( this . path + key , 'utf8' ) ) ;
16+ }
17+ has ( key ) {
18+ return this . fs . existsSync ( this . path + key ) ;
19+ }
20+ delete ( key ) {
21+ this . fs . unlinkSync ( this . path + key ) ;
22+ }
23+ get size ( ) {
24+ return this . keys ( ) . length ;
25+ }
26+ keys ( ) {
27+ return this . fs . readdirSync ( this . path ) ;
28+ }
29+ clear ( ) {
30+ this . keys ( ) . forEach ( file => {
31+ this . delete ( file ) ;
32+ } ) ;
33+ }
34+ }
35+
36+ // Usage
37+
38+ const fs = require ( 'fs' ) ;
39+ const dict = new HashMap ( fs , './data/' ) ;
40+ dict . set ( 'name' , 'Marcus' ) ;
41+ dict . set ( 'born' , '121-04-26' ) ;
42+ dict . set ( 'city' , 'Roma' ) ;
43+ dict . set ( 'position' , 'Emperor' ) ;
44+ dict . delete ( 'city' ) ;
45+ console . dir ( {
46+ name : dict . get ( 'name' ) ,
47+ size : dict . size ,
48+ has : {
49+ name : dict . has ( 'name' ) ,
50+ city : dict . has ( 'city' ) ,
51+ } ,
52+ keys : dict . get ( 'name' ) ,
53+ } ) ;
54+
55+ dict . clear ( ) ;
Original file line number Diff line number Diff line change 1- # Adapter
2- Pattern Adapter Implementations
1+ # Pattern Adapter Implementations
You can’t perform that action at this time.
0 commit comments