Append with automatic resize
JavaScriptclass DynamicArray {
constructor() {
this.data = new Array(2);
this.size = 0;
this.capacity = 2;
}
append(value) {
if (this.size === this.capacity) {
const newData = new Array(this.capacity * 2);
for (let i = 0; i < this.size; i++) {
newData[i] = this.data[i];
}
this.data = newData;
this.capacity *= 2;
}
this.data[this.size] = value;
this.size++;
}
}
const arr = new DynamicArray();
arr.append(10);
arr.append(25);
arr.append(37);
console.log(arr.data.slice(0, arr.size));
console.log(arr.capacity);Explanation
The first two appends fit in the original buffer. The third append detects that size equals capacity, allocates a new array with double capacity, copies old elements, and then writes the new value.
Output
[10, 25, 37] 4
Real-life Example
A photo gallery app keeps extra reserved slots so adding one more image usually does not require rebuilding the whole gallery structure every single time.