File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
'use strict';
2+
3+
class Cache {
4+
constructor() {
5+
const proto = Object.getOf(this);
6+
if (proto.constructor === Cache) {
7+
throw new Error('Abstract class should not be instanciated');
8+
}
9+
this.allocated = 0;
10+
}
11+
12+
read(key) {
13+
const s = JSON.stringify({ read: { key } });
14+
throw new Error('Method is not implemented: ' + s);
15+
}
16+
17+
add(key, val) {
18+
const s = JSON.stringify({ add: { key, val } });
19+
throw new Error('Method is not implemented: ' + s);
20+
}
21+
22+
delete(key) {
23+
const s = JSON.stringify({ delete: { key } });
24+
throw new Error('Method is not implemented: ' + s);
25+
}
26+
}
27+
28+
class MapCache extends Cache {
29+
constructor() {
30+
super();
31+
this.data = new Map();
32+
}
33+
34+
read(key) {
35+
return this.data.get(key);
36+
}
37+
38+
add(key, val) {
39+
const prev = this.data.get(key);
40+
if (prev) this.allocated -= prev.length;
41+
this.allocated += val.length;
42+
this.data.set(key, val);
43+
}
44+
45+
delete(key) {
46+
const val = this.data.get(key);
47+
if (val) {
48+
this.allocated -= val.length;
49+
this.data.delete(key);
50+
}
51+
}
52+
}
53+
54+
class ObjectCache extends Cache {
55+
constructor() {
56+
super();
57+
this.data = {};
58+
}
59+
60+
read(key) {
61+
return this.data[key];
62+
}
63+
64+
add(key, val) {
65+
const prev = this.data[key];
66+
if (prev) this.allocated -= prev.length;
67+
this.allocated += val.length;
68+
this.data[key] = val;
69+
}
70+
71+
delete(key) {
72+
const val = this.data[key];
73+
if (val) {
74+
this.allocated -= val.length;
75+
delete this.data[key];
76+
}
77+
}
78+
}
79+
80+
// Usage
81+
82+
const mapCache = new MapCache();
83+
mapCache.add('key1', 'value1');
84+
mapCache.add('key2', 'value2');
85+
mapCache.delete('key2');
86+
console.dir(mapCache);
87+
88+
const objCache = new ObjectCache();
89+
objCache.add('key1', 'value1');
90+
objCache.add('key2', 'value2');
91+
objCache.delete('key2');
92+
console.dir(objCache);

0 commit comments

Comments
 (0)