From cd080aa2a360a1955b8fbb9b8082dfbceb84c1f0 Mon Sep 17 00:00:00 2001 From: James Prevett Date: Sat, 16 Nov 2024 16:28:07 -0600 Subject: [PATCH] Added `List.insert` Changed `List.entries` and `List.keys` to have array behavior --- src/list.ts | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/src/list.ts b/src/list.ts index a47a367..205722a 100644 --- a/src/list.ts +++ b/src/list.ts @@ -28,17 +28,21 @@ export class List extends EventEmitter<'update'> implements RelativeIndexable return this.join(','); } - public set(index: number, value: T): void { + protected _set(index: number, value: T, _delete: boolean = false) { if (Math.abs(index) > this.data.size) { throw new ReferenceError('Can not set an element outside the bounds of the list'); } const data = Array.from(this.data); - data.splice(index, 1, value); + data.splice(index, +_delete, value); this.data = new Set(data); this.emit('update'); } + public set(index: number, value: T): void { + this._set(index, value, true); + } + public deleteAt(index: number): void { if (Math.abs(index) > this.data.size) { throw new ReferenceError('Can not delete an element outside the bounds of the list'); @@ -47,6 +51,10 @@ export class List extends EventEmitter<'update'> implements RelativeIndexable this.delete(Array.from(this.data).at(index)!); } + public insert(value: T, index: number = this.data.size) { + this._set(index, value, false); + } + // Array methods public at(index: number): T { @@ -115,12 +123,14 @@ export class List extends EventEmitter<'update'> implements RelativeIndexable return this.data.size; } - public entries(): IterableIterator<[T, T]> { - return this.data.entries(); + // Iteration + + public entries(): IterableIterator<[number, T]> { + return this.toArray().entries(); } - public keys(): IterableIterator { - return this.data.keys(); + public keys(): IterableIterator { + return this.toArray().keys(); } public values(): IterableIterator {