Skip to main content

ArrayList

ArrayList is a data structure that use the serialize memory to store data. So we can easily to use index to find the data with constant time complexity which is O(1). In contrast, if we want to delete or insert the new data in the middle of the collection, we have to shift the rest of data to the left or right, which is cost O(n) to do that.

Implementation

class ArrayList {
constructor(){
this.list = {}
this.length = 0
}

pop(){
if (this.length){
const lastIdx = this.length - 1
const value = this.list[lastIdx]

delete this.list[lastIdx]
this.length--

return value
} else {
return void 0
}
}

push(value){
this.list[this.length] = value
this.length++
}

get(index){
return this.list[index]
}

delete(index){
const value = this.list[index]

if (!value){
return void 0
}

for (let i = index; i < this.length; i++){
this.list[index] = this.list[index + 1]
}

delete this.list[this.length - 1]
this.length--

return value
}

}