程式碼:
class JList {
#arr = new Array();
#capacity = 10;
#size = 0;
#extendRatio = 2;
constructor() {
this.#arr = new Array(this.#capacity);
}
/**
* 獲取列表中元素的數量
* @returns
*/
size() {
return this.#size;
}
/**
* 獲取列表總容量
* @returns
*/
capacity() {
return this.#capacity;
}
/**
* 訪問某個索引上的元素
* @param {number} index
*/
get(index) {
if (index < 0 || index >= this.#size) {
throw new Error('索引越界');
}
return this.#arr[index];
}
/**
* 更新某個位置上的元素
* @param {number} index
* @param {number} num
*/
set(index, num) {
if (index < 0 || index >= this.#size) {
throw new Error('索引越界');
}
this.#arr[index] = num;
}
/**
* 擴容
*/
extendCapacity() {
this.#arr = this.#arr.concat(new Array(this.capacity() * (this.#extendRatio - 1)));
this.#capacity = this.#arr.length;
}
/**
* 向任意位置插入元素
* @param {number} index
* @param {number} num
*/
insert(index, num) {
if (index < 0 || index > this.#size) {
throw new Error('索引越界');
}
if (this.#size === this.#capacity) {
this.extendCapacity();
}
// 將當前處於index位置及之後的元素分別向後移動一位(空出index位,然後再插入)
for (let j = this.#size - 1; j >= index; j--) {
this.#arr[j + 1] = this.#arr[j];
}
this.#arr[index] = num;
this.#size += 1;
}
/**
* 向尾部新增元素
* @param {number} num
*/
add(num) {
this.insert(this.#size, num);
}
/**
* 移除某個位置的元素
* @param {number} index
*/
remove(index) {
if (index < 0 || index >= this.#size) {
throw new Error('索引越界');
}
let num = this.#arr[index];
const len = this.#size - 1;
// 從index位置開始,之後的每個元素依次向前移動一位
for (let i = index; i < len; i++) {
this.#arr[j] = this.#arr[j + 1];
}
this.#size -= 1;
return num;
}
/**
* 轉為陣列進行輸出
* (虛擬碼)
* @returns
*/
toArray() {
const n = this.#size;
const arr = new Array(n);
for (let i = 0; i < n; i++) {
arr[i] = this.get(i);
}
return arr;
//// 等同於
//// return [...this.#arr];
}
}