-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamicArray.ts
More file actions
71 lines (53 loc) · 1.45 KB
/
DynamicArray.ts
File metadata and controls
71 lines (53 loc) · 1.45 KB
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
export class DynamicArray<T> {
#array: Array<T>;
#size: number;
constructor(capacity = 1) {
if (capacity <= 0) throw new Error("Capacity must be greater than zero");
this.#array = new Array<T>(capacity);
this.#size = 0;
}
get size(): number {
return this.#size;
}
get capacity(): number {
return this.#array.length;
}
push(item: T): void {
// If the array is full, double its size
if (this.size == this.capacity) this.#resize(this.capacity * 2);
this.#array[this.#size++] = item;
}
pop(): T {
if (this.#size == 0) return undefined as T;
this.#size--;
// If the array is only one quarter full, shrink to half the size
if (this.#size <= this.capacity / 4 && this.#size > 0) {
this.#resize(this.capacity / 2);
}
return this.#array[this.#size];
}
get(index: number): T {
if (index < 0 || index >= this.#size)
throw new Error("Index is out of bounds");
return this.#array[index];
}
#resize(newCapacity: number): void {
const newArray = new Array<T>(newCapacity);
// Copy values in the old array to the new one
for (let i = 0; i < this.#size; i++) {
newArray[i] = this.#array[i];
}
this.#array = newArray;
}
toString(): string {
let res = "";
for (let i = 0; i < this.#size; i++) {
const item = this.#array[i];
res += `${item}`;
if (i < this.#size - 1) {
res += ",";
}
}
return res;
}
}