Binato/server/objects/FunkyArray.ts

74 lines
1.6 KiB
TypeScript
Raw Normal View History

2023-09-10 12:59:22 +01:00
export default class FunkyArray<T> {
2023-10-04 12:28:47 +01:00
private items:{ [id: string]: T } = {};
2022-11-16 15:25:46 +00:00
private itemKeys:Array<string> = Object.keys(this.items);
private iterableArray:Array<T> = new Array<T>();
2022-11-19 01:06:03 +00:00
public add(key:string, item:T, regenerate:boolean = true) : T {
this.items[key] = item;
2022-11-16 15:25:46 +00:00
if (regenerate) {
this.itemKeys = Object.keys(this.items);
this.regenerateIterableArray();
}
2022-11-19 01:06:03 +00:00
return this.items[key];
2022-11-16 15:25:46 +00:00
}
2022-11-19 01:06:03 +00:00
public remove(key:string, regenerate:boolean = true) {
delete this.items[key];
2022-11-16 15:25:46 +00:00
if (regenerate) {
this.itemKeys = Object.keys(this.items);
this.regenerateIterableArray();
}
}
public removeFirstItem(regenerate:boolean = true) : void {
delete this.items[this.itemKeys[0]];
this.itemKeys = Object.keys(this.items);
if (regenerate) this.regenerateIterableArray();
}
public regenerateIterableArray() : void {
2023-10-04 15:10:38 +01:00
this.iterableArray = new Array<T>();
for (const itemKey of this.itemKeys) {
2022-11-16 15:25:46 +00:00
this.iterableArray.push(this.items[itemKey]);
}
this.itemKeys = Object.keys(this.items);
}
public getFirstItem() : T {
return this.items[this.itemKeys[0]];
}
public getLength() : number {
return this.itemKeys.length;
}
public getKeyById(id:number) : string {
return this.itemKeys[id];
}
public getById(id:number) : T | undefined {
return this.items[this.itemKeys[id]];
}
public getByKey(key:string) : T | undefined {
if (key in this.items) {
return this.items[key];
}
return undefined;
}
public getKeys() : Array<string> {
return this.itemKeys;
}
2023-10-04 15:10:38 +01:00
public getItems() : { [id: string]: T } {
2022-11-16 15:25:46 +00:00
return this.items;
}
public getIterableItems() : Array<T> {
return this.iterableArray;
}
}