JS 列表 - 随笔
代码:
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];
}
}