-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
98 lines (77 loc) · 2.15 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
'use strict';
process.stdin.setEncoding('utf8');
const pages = [];
pages.push({});
process.stdin.on('readable', () => {
let chunk;
while ((chunk = process.stdin.read()) !== null) {
if (!chunk.trim()) return;
const params = chunk
.split(/\s/)
.filter(p => !!p)
.map(p => p.trim())
;
const cmdName = params.shift();
if (!cmdName) return;
const command = commands[cmdName.toUpperCase()];
if (command instanceof Function) {
const result = command(params);
if (result !== undefined && result !== null) {
console.log(result);
}
} else {
console.log(`${cmdName} is not a valid command`);
}
}
});
const commands = {
"SET": params => {
const [key, val] = params.splice(0,2);
if (!key) return;
getCurrentPage()[key] = val;
},
"GET": params => {
const key = params.shift();
if (!key) return;
const val = getCurrentPage()[key];
return val || "NULL";
},
"UNSET": params => {
const key = params.shift();
getCurrentPage()[key] = undefined;
},
"NUMEQUALTO": params => {
const val = params.shift();
const page = getCurrentPage();
return Object.keys(page).reduce((count, key) => {
if (page[key] === val) count++;
return count;
}, 0);
},
"BEGIN": () => {
// NB: shallow copy!
const page = {...pages[pages.length-1]};
pages.push(page);
},
"COMMIT": () => {
if (pages.length === 1) return "NO TRANSACTION";
const length = pages.length;
for (let i = length - 1; i > 0; i--) {
let current = pages[i];
let prev = pages[i-1];
// NB: shallow copy!
pages[i-1] = {...prev, ...current};
pages.pop();
}
},
"ROLLBACK": () => {
if (pages.length === 1) return "NO TRANSACTION";
pages.pop();
},
"END": () => {
process.exit(0);
}
};
function getCurrentPage() {
return pages[pages.length-1];
}