Skip to content

Commit 800aa1e

Browse files
committed
Implement interface adapter: fs to Map
1 parent d12907c commit 800aa1e

File tree

2 files changed

+56
-2
lines changed

2 files changed

+56
-2
lines changed

JavaScript/6-interface.js

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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();

README.md

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1 @@
1-
# Adapter
2-
Pattern Adapter Implementations
1+
# Pattern Adapter Implementations

0 commit comments

Comments
 (0)