Skip to content

Instantly share code, notes, and snippets.

@negarjf
Created July 24, 2019 17:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save negarjf/8f1aa8c1458d6b869c5178c5579d9e10 to your computer and use it in GitHub Desktop.
Save negarjf/8f1aa8c1458d6b869c5178c5579d9e10 to your computer and use it in GitHub Desktop.
Dynamic Array Javascript: https://repl.it/@NegarJF/Dynamic-array
class DynamicArray{
constructor(capacity){
this.arr = [];
this.capacity = capacity;
this.length = 0;
for(let i = 0; i < capacity; i++){
this.arr[i] = null;
}
}
get size() {
return this.length;
}
get isEmpty(){
return this.size === 0
}
get(index){
return this.arr[index];
}
set(index, element){
if(index < 0 || index > this.size){
console.error('Out of Rane');
return;
}
this.arr[index] = element;
this.length++;
}
cheat(){
return this.arr;
}
add(element){
if(this.size >= this.capacity){
this.capacity = this.capacity * 2;
let newArray = [];
for(let i = 0; i < this.capacity; i++){
if(i < this.size) {
newArray[i] = this.arr[i];
}else{
newArray[i] = null;
}
}
this.arr = newArray;
}
this.arr[this.size] = element;
this.length++;
}
removeAt(rm_index){
if(rm_index < 0 || rm_index > this.size){
console.error('Out of Rane');
return;
}
let data = this.arr[rm_index];
let newArray = [];
for(let i = 0, j = 0; i < this.size; i++, j++){
if(i === rm_index){
j--;
}else{
newArray[j] = this.arr[i];
}
}
this.arr = newArray;
this.length--;
this.capacity = this.size;
return data;
}
clear(){
for(let i= 0; i< this.size; i++){
this.arr[i] = null;
}
this.length = 0;
}
};
module.exports = DynamicArray;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment