forked from yfcheng/hackerrank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
simpleDatabase.js
76 lines (69 loc) · 1.55 KB
/
simpleDatabase.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
#!/usr/local/bin/node
/*
SET a 10
SET b 10
NUMEQUALTO 10 2
NUMEQUALTO 20 0
SET b 30
NUMEQUALTO 10 1
END
*/
function SimpleDatabase()
{
// .. private variables
var reverseLookup = {},
dataBag = {};
// .. private methods
var update = function (dict, key, incr){
if(!dict[key]){
dict[key] = incr;
}
else{
dict[key] += incr;
}
},
set = function(args){
var key = args[1],
value = parseInt( args[2] );
key = key.toString();
update(dataBag, key, value);
update(reverseLookup, value, 1);
},
numEqualTo = function(args){
var key = args[1];
key = key.toString();
return (reverseLookup[key] ? reverseLookup[key] : '');
},
get = function(args){
var key = args[1];
key = key.toString();
return dataBag[key];
},
unset = function(args){
var key = args[1],
val = dataBag[key];
delete dataBag[key];
reverseLookup[val] -= 1;
};
// .. public methods
this.processCommand = function(cmd){
var args = cmd.split('\n'),
args = args[0].split(' ');
// if(args && Array.isArray(args) && args.length > 0){} // .. do validation of the input args
switch(args[0]){
case 'SET':
return set(args);
case 'NUMEQUALTO':
return numEqualTo(args);
case 'UNSET':
return unset(args);
case 'GET':
return get(args);
case 'END':
dataBag = {};
reverseLookup = {};
break;
}
};
}
module.exports = SimpleDatabase;