-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
97 lines (82 loc) · 2.06 KB
/
index.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
interface KV<T> {
[key: number]: T[];
}
export default class OrderedMapArray<T> {
private data: KV<T> = {};
constructor() {
this.data = {}
}
public clear() {
this.data = {}
}
public remove(key: number): void {
delete this.data[key]
}
public get(key: number): T[] {
return this.data[key]
}
public set(key: number, value: T): void {
this.data[key] = [value];
}
public push(key: number, value: T): void {
if (this.data[key] === undefined) {
this.data[key] = [];
}
this.data[key].push(value)
}
public prepend(key: number, value: T): void {
if (this.data[key] === undefined) {
this.data[key] = [];
}
this.data[key].unshift(value);
}
public concat(key: number, values: T[]): void {
if (this.data[key] === undefined) {
this.data[key] = [...values];
return
}
this.data[key] = this.data[key].concat(values)
}
public first(): T | undefined {
const key = this.firstKey()
if (key === undefined) {
return
}
return this.data[key][0]
}
public last(): T | undefined {
const key = this.lastKey()
if (key === undefined) {
return
}
const values = this.data[key]
return values[values.length - 1]
}
public firstKey(): number | undefined {
return this.keys()[0]
}
public lastKey(): number | undefined {
const keys = this.keys()
return keys[keys.length - 1]
}
/**
* returns all values in order
*/
public values(): T[] {
const res: T[] = []
for (let key of this.keys()) {
for (let value of this.data[key]) {
res.push(value)
}
}
return res;
}
/**
* returns all keys in order
*/
public keys(): number[] {
return Object.keys(this.data)
.map(k => parseInt(k, 10))
.sort((a, b) => a - b)
}
}