forked from VladislavPixel/home-work-cs-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dynamic-array.ts
74 lines (53 loc) · 1.58 KB
/
dynamic-array.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
import LinkedList from "./linked-list";
import type { IDynamicArray, ILinkedList } from "../types/interfaces";
class DynamicArray<T> implements IDynamicArray<T> {
#list: ILinkedList<T>;
#capacityArr: number;
#counterForTailNode: number;
#length: number;
constructor(capacityValue: number = 3) {
this.#capacityArr = capacityValue;
this.#length = 0;
this.#counterForTailNode = -1;
this.#list = new LinkedList<T>();
(() => {
this.#list.add(new Array(this.#capacityArr));
})();
}
add(newValue: T): number {
if (this.#capacityArr === 0) {
throw new Error(
"method `add` is not supported in DynamicArray with 0 capacity value"
);
}
if (this.#counterForTailNode === this.#capacityArr - 1) {
this.#list.add(new Array(this.#capacityArr));
this.#counterForTailNode = -1;
}
this.#counterForTailNode++;
if (this.#list.last && Array.isArray(this.#list.last.value)) {
this.#list.last.value[this.#counterForTailNode] = newValue;
this.#length++;
}
return this.#length;
}
get(indexForElement: number): undefined | T {
if (indexForElement >= this.#length || indexForElement < 0) {
return undefined;
}
const numberNode = Math.floor(indexForElement / this.#capacityArr);
const targetIndexForArr = indexForElement % this.#capacityArr;
let startIndex = 0;
for (const nodeInfo of this.#list) {
if (startIndex === numberNode && Array.isArray(nodeInfo!.value)) {
return nodeInfo!.value[targetIndexForArr];
}
startIndex++;
}
return undefined;
}
get length(): number {
return this.#length;
}
}
export default DynamicArray;