-
Notifications
You must be signed in to change notification settings - Fork 1
/
numbermap.ts
75 lines (62 loc) · 1.67 KB
/
numbermap.ts
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
export class NumberMap<V>{
/** @internal */
private _keyCount = 0;
/** @internal */
private _map: {[key: number]: V} = Object.create(null);
constructor(source?: [number,V][]) {
if(source) {
for(const [k,v] of source) {
this.set(k,v);
}
}
}
clear() {
this._map = Object.create(null);
this._keyCount = 0;
}
delete(key: number): boolean {
const had = this.has(key);
delete this._map[key];
if(had) {
this._keyCount -= 1;
}
return had;
}
forEach(callback: (value: V, key: number, map: NumberMap<V>) => void, thisArg?: any): void {
for(const key in this._map) {
callback.call(thisArg, this._map[key], key, this);
}
}
get(key: number): V | undefined {
return this._map[key];
}
has(key: number): boolean {
return key in this._map;
}
set(key: number, value: V): this {
const had = this.has(key);
this._map[key] = value;
if(!had) {
this._keyCount += 1;
}
return this;
}
get size(): number {
return this._keyCount;
}
values(): V[] {
const values: V[] = [];
for(const key in this._map) values.push(this._map[key]);
return values;
}
keys(): number[] {
const keys = [];
for(const key in this._map) keys.push(+key);
return keys as any; // index typings
}
entries(): [number,V][] {
const entries = [];
for(const key in this._map) entries.push([+key, this._map[key]]);
return entries as any; // index typings
}
}