Skip to content

Commit 4fdce31

Browse files
Merge pull request #45 from wakidurrahman/feat/array-02
array created
2 parents f75dad1 + 4ae4ffc commit 4fdce31

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* DataStructure: Array Implementation
3+
* Arrays in JavaScript are just objects with integer based keys that act like indexes,
4+
*/
5+
6+
class Array01 {
7+
constructor() {
8+
this.length = 0; // Declare length of the array
9+
this.data = {}; // Store date inside array.
10+
}
11+
12+
// Get Method O(1)
13+
get(index) {
14+
return this.data[index];
15+
}
16+
17+
// Push method O(1)
18+
push(item) {
19+
this.data[this.length] = item; // Insert item into last index.
20+
this.length++; // Increment index.
21+
return this.data; // return array
22+
}
23+
24+
// Pop method O(1)
25+
pop() {
26+
const lastItem = this.data[this.length - 1]; // last index
27+
delete this.data[this.length - 1]; // delete last index
28+
this.length--; // decrease length of the array.
29+
return lastItem; // return last item
30+
}
31+
32+
// Delete method O(n)
33+
deleteAtIndex(index) {
34+
const item = this.data[index]; // track item specific index
35+
this.shiftItems(index); // ShiftItem place.
36+
return item;
37+
}
38+
39+
// Private function.
40+
shiftItems(index) {
41+
for (let i = index; i < this.length - 1; i++) {
42+
this.data[i] = this.data[i + 1];
43+
}
44+
console.log(this.data[this.length - 1]);
45+
delete this.data[this.length - 1]; // delete last index of the array
46+
this.length--;
47+
}
48+
}
49+
50+
const myArray = new Array01();
51+
myArray.push("hi");
52+
myArray.push("you");
53+
myArray.push("!");
54+
myArray.pop();
55+
myArray.deleteAtIndex(0);
56+
myArray.push("are");
57+
myArray.push("nice");
58+
myArray.shiftItems(0);
59+
console.log(myArray);

0 commit comments

Comments
 (0)