-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamicArray.js
More file actions
102 lines (94 loc) · 2.16 KB
/
DynamicArray.js
File metadata and controls
102 lines (94 loc) · 2.16 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
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
98
99
100
101
102
class DynamicArray {
/**
* @constructor
* @param {number} capacity
*/
constructor(capacity) {
if (capacity <= 0) {
throw new Error("Capacity must be greater than 0");
}
this.array = new Array(capacity);
this.size = 0;
this.capacity = capacity;
}
/**
*
* @param {number} i
* @returns {number}
*/
get(i) {
if (i < 0 || i >= this.size) {
throw new Error("Index out of bounds");
}
return this.array[i];
}
/**
*
* @param {number} i
* @param {number} n
*/
set(i, n) {
if (i < 0 || i >= this.size) {
throw new Error("Index out of bounds");
}
this.array[i] = n;
}
/**
*
* @param {number} n
*/
pushBack(n) {
if (this.size === this.capacity) {
this.resize();
}
this.array[this.size] = n;
this.size++;
}
/**
*
* @returns {number} value
*/
popBack() {
if (this.size === 0) {
throw new Error("Array is empty");
}
const value = this.array[this.size - 1];
this.size--;
return value;
}
/**
* double the capacity of the array
*/
resize() {
this.capacity *= 2;
const newArray = new Array(this.capacity);
for (let i = 0; i < this.size; i++) {
newArray[i] = this.array[i];
}
this.array = newArray;
}
/**
*
* @returns {number}
*/
getSize() {
return this.size;
}
getCapacity() {
return this.capacity;
}
}
// Example Usage:
let arr = new DynamicArray(1);
console.log(arr.getSize()); // Output: 0
console.log(arr.getCapacity()); // Output: 1
arr.pushBack(1);
console.log(arr.getCapacity()); // Output: 1
arr.pushBack(2);
console.log(arr.getCapacity()); // Output: 2
console.log(arr.get(1)); // Output: 2
arr.set(1, 3);
console.log(arr.get(1)); // Output: 3
console.log(arr.popBack()); // Output: 3
console.log(arr.getSize()); // Output: 1
console.log(arr.getCapacity()); // Output: 2