Last active
April 19, 2021 09:11
-
-
Save darshna09/e191ea82efdde78bb7ce611ff19f6f9e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class OurArray { | |
constructor () { | |
this.length = 0; | |
this.data = {}; // An array in JavaScript is Object | |
} | |
/** Lookup: Time Complexity = O(1) | |
* @param {number} index | |
* @return {any} item | |
*/ | |
get (index) { | |
return this.data[index]; | |
} | |
/** | |
* Time Complexity = O(1) | |
* @param {any} item | |
* @return {number} length | |
* New length of the array | |
*/ | |
push (item) { | |
this.data[this.length] = item; | |
this.length++; | |
return this.length; // JavaScript `push` method returns the new length of the array | |
} | |
/** | |
* Time Complexity = O(1) | |
* @return {number} lastItem | |
*/ | |
pop () { | |
const lastItem = this.data[this.length - 1]; | |
delete this.data[this.length - 1]; | |
this.length--; | |
return lastItem; | |
} | |
/** | |
* Time Complexity = O(N) | |
* @param {number} index | |
* Index of the item to be deleted | |
* @return {any} item | |
* Deleted item | |
*/ | |
deleteAtIndex (index) { | |
const item = this.data[index]; | |
this.shiftItems(index); // Shift the elements | |
return item; | |
} | |
/** | |
* Called from deleteAtIndex | |
* Shift Items towards left from the index where the item has to be deleted. | |
* @param {number} index | |
*/ | |
shiftItems(index) { | |
for (let i = index; i < this.length - 1; i++) { | |
this.data[i] = this.data[i + 1]; // The item at index is replaced. | |
} | |
delete this.data[this.length - 1]; // Removing the last item. | |
this.length--; | |
} | |
} | |
const myThings = new OurArray(); | |
myThings; // { length: 0, data: {} } | |
myThings.get(0); // undefined | |
myThings.push('Books'); // 1 | |
myThings.push('Car'); // 2 | |
myThings.pop(); // 'Car' | |
myThings.push('House'); // 2 | |
myThings.deleteAtIndex(1); // 'House' | |
myThings.get(0); // 'Books' | |
myThings; // { length: 1, data: { '0': 'Books' } } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment