|
| 1 | +// ! Day 2 of learning DSA in Javascript |
| 2 | + |
| 3 | +// * Topic (Array Data Structure) |
| 4 | + |
| 5 | +// Todo: Array Method list: |
| 6 | + |
| 7 | +// * 1, push() --> adds a new element to the end of an array and returns the new length of an array, |
| 8 | +// * 2, Get() --> get the element by it's index from an array and returns the element |
| 9 | +// * 3, pop() --> removes the last element of an array and return the removed element, |
| 10 | +// * 4, shift() --> removes the first element of an array and return the removed element, |
| 11 | + |
| 12 | +class MyArray { |
| 13 | + constructor() { |
| 14 | + this.length = 0; |
| 15 | + this.data = {}; |
| 16 | + } |
| 17 | + push(item) { |
| 18 | + this.data[this.length] = item; |
| 19 | + this.length++; |
| 20 | + return this.length; |
| 21 | + } |
| 22 | + get(index) { |
| 23 | + return this.data[index]; |
| 24 | + } |
| 25 | + pop() { |
| 26 | + const lastElement = this.data[this.length - 1]; |
| 27 | + delete this.data[this.length - 1]; |
| 28 | + this.length--; |
| 29 | + return lastElement; |
| 30 | + } |
| 31 | + |
| 32 | + shift() { |
| 33 | + const firstElement = this.data[0]; |
| 34 | + for (let i = 0; i < this.length; i++) { |
| 35 | + this.data[i] = this.data[i + 1]; |
| 36 | + } |
| 37 | + delete this.data[this.length - 1]; |
| 38 | + this.length--; |
| 39 | + return firstElement; |
| 40 | + } |
| 41 | + delete(index) { |
| 42 | + const deletedElement = this.data[index]; |
| 43 | + |
| 44 | + for (let i = index; i < this.length - 1; i++) { |
| 45 | + this.data[i] = this.data[i + 1]; |
| 46 | + } |
| 47 | + |
| 48 | + delete this.data[this.length - 1]; |
| 49 | + this.length--; |
| 50 | + |
| 51 | + return deletedElement; |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +const MyNewArray = new MyArray(); |
| 56 | + |
| 57 | +console.log(MyNewArray.push("apple")); |
| 58 | +console.log(MyNewArray.push("mango")); |
| 59 | +console.log(MyNewArray.push("orange")); |
| 60 | +console.log(MyNewArray.push("banana")); |
| 61 | + |
| 62 | +console.log(MyNewArray); |
| 63 | + |
| 64 | +console.log(MyNewArray.get(2)); |
| 65 | +console.log(MyNewArray.pop()); |
| 66 | +console.log(MyNewArray.shift()); |
| 67 | +console.log(MyNewArray.delete(1)); |
| 68 | + |
| 69 | +console.log(MyNewArray); |
0 commit comments