-
Notifications
You must be signed in to change notification settings - Fork 0
/
sorted-array-list.ts
82 lines (64 loc) · 1.98 KB
/
sorted-array-list.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
import { binarySearch, sortedInsert, sortedRemove } from "../../../utils/sorted-array-utils";
import { List } from "./list";
export class SortedArrayList<T> implements List<T> {
private readonly data: T[] = [];
public constructor(private readonly comparator: (a: T, b: T) => number) {
}
public forEach(callback: (item: T, index: number) => boolean): void {
this.data.forEach(callback);
}
public getItem(index: number): T | undefined {
if (index < 0 || index >= this.length) {
return;
}
return this.data[index];
}
public [Symbol.iterator](): IterableIterator<T> {
let current = 0;
return {
[Symbol.iterator](): IterableIterator<T> {
return this;
},
next: (): IteratorResult<T> => {
if (current < this.data.length) {
return {
value: this.data[current++],
done : false,
};
}
return {
value: undefined,
done : true,
};
},
};
}
public get length(): number {
return this.data.length;
}
public get empty(): boolean {
return this.data.length === 0;
}
public add(item: T): number {
return sortedInsert(this.data, item, this.comparator);
}
public removeItemAt(index: number): boolean {
if (index < 0 || index >= this.length) {
return false;
}
this.data.splice(index, 1);
return true;
}
public clear(): void {
this.data.splice(0, this.data.length);
}
public contains(item: T): boolean {
return binarySearch(this.data, item, this.comparator) >= 0;
}
public remove(item: T): boolean {
return !!sortedRemove(this.data, item, this.comparator);
}
public toArray(): T[] {
return [...this.data];
}
}