File tree Expand file tree Collapse file tree 2 files changed +59
-0
lines changed
src/course-master-the-coding/data-structures/arrays Expand file tree Collapse file tree 2 files changed +59
-0
lines changed Original file line number Diff line number Diff line change
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 ) ;
File renamed without changes.
You can’t perform that action at this time.
0 commit comments