-
Notifications
You must be signed in to change notification settings - Fork 412
/
TypedMap.js
36 lines (32 loc) · 1.34 KB
/
TypedMap.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
class TypedMap extends Map {
constructor(keyType, valueType, entries) {
// If entries are specified, check their types
if (entries) {
for(let [k, v] of entries) {
if (typeof k !== keyType || typeof v !== valueType) {
throw new TypeError(`Wrong type for entry [${k}, ${v}]`);
}
}
}
// Initialize the superclass with the (type-checked) initial entries
super(entries);
// And then initialize this subclass by storing the types
this.keyType = keyType;
this.valueType = valueType;
}
// Now redefine the set() method to add type checking for any
// new entries added to the map.
set(key, value) {
// Throw an error if the key or value are of the wrong type
if (this.keyType && typeof key !== this.keyType) {
throw new TypeError(`${key} is not of type ${this.keyType}`);
}
if (this.valueType && typeof value !== this.valueType) {
throw new TypeError(`${value} is not of type ${this.valueType}`);
}
// If the types are correct, we invoke the superclass's version of
// the set() method, to actually add the entry to the map. And we
// return whatever the superclass method returns.
return super.set(key, value);
}
}