Files
lik/ts/classes.fastmap.ts

112 lines
2.5 KiB
TypeScript
Raw Normal View History

2022-05-27 17:53:02 +02:00
/* ============
The FastMap has the goal of creating the fastes to use map possible in JS
============ */
2024-02-25 13:01:06 +01:00
import * as plugins from './classes.plugins.js';
2020-05-25 22:18:41 +00:00
/**
* fast map allows for very quick lookups of objects with a unique key
*/
2020-02-06 11:11:16 +00:00
export class FastMap<T> {
private mapObject = new Map<string, T>();
2020-02-06 11:11:16 +00:00
public isUniqueKey(keyArg: string): boolean {
return !this.mapObject.has(keyArg);
}
public has(keyArg: string): boolean {
return this.mapObject.has(keyArg);
}
public get size(): number {
return this.mapObject.size;
}
public addToMap(
keyArg: string,
objectArg: T,
optionsArg?: {
force: boolean;
}
): boolean {
if (this.isUniqueKey(keyArg) || (optionsArg && optionsArg.force)) {
this.mapObject.set(keyArg, objectArg);
return true;
} else {
return false;
}
}
public getByKey(keyArg: string): T | undefined {
return this.mapObject.get(keyArg);
}
2021-09-12 15:39:47 +02:00
public removeFromMap(keyArg: string): T {
const removedItem = this.mapObject.get(keyArg);
this.mapObject.delete(keyArg);
return removedItem;
}
2020-02-06 11:11:16 +00:00
public getKeys(): string[] {
return Array.from(this.mapObject.keys());
}
public values(): T[] {
return Array.from(this.mapObject.values());
}
public entries(): [string, T][] {
return Array.from(this.mapObject.entries());
2020-02-06 11:11:16 +00:00
}
2020-02-16 23:15:50 +00:00
public clean() {
this.mapObject.clear();
2020-02-16 23:15:50 +00:00
}
/**
2021-09-12 15:39:47 +02:00
* returns a new Fastmap that includes all values from this and all from the fastmap in the argument
*/
public concat(fastMapArg: FastMap<T>) {
const concatedFastmap = new FastMap<T>();
for (const key of this.getKeys()) {
concatedFastmap.addToMap(key, this.getByKey(key));
}
for (const key of fastMapArg.getKeys()) {
concatedFastmap.addToMap(key, fastMapArg.getByKey(key), {
2020-07-12 00:44:50 +00:00
force: true,
});
}
return concatedFastmap;
}
/**
2021-09-12 15:39:47 +02:00
* tries to merge another Fastmap
* Note: uniqueKeyCollisions will cause overwrite
2021-09-12 15:39:47 +02:00
* @param fastMapArg
*/
public addAllFromOther(fastMapArg: FastMap<T>) {
for (const key of fastMapArg.getKeys()) {
this.addToMap(key, fastMapArg.getByKey(key), {
2020-07-12 00:44:50 +00:00
force: true,
});
}
}
2021-09-12 15:39:47 +02:00
2021-09-12 16:08:20 +02:00
public async find(findFunctionArg: (mapItemArg: T) => Promise<boolean>) {
2021-09-12 15:39:47 +02:00
for (const key of this.getKeys()) {
2021-09-12 16:08:20 +02:00
const item = this.getByKey(key);
const findFunctionResult = await findFunctionArg(item);
if (findFunctionResult) {
return item;
}
2021-09-12 15:39:47 +02:00
}
}
public [Symbol.iterator](): Iterator<[string, T]> {
return this.mapObject.entries();
}
2020-02-06 11:11:16 +00:00
}