I need to do a set of Arrays. Javascript's default Set does not work with arrays, so I added this new Typescript class:
export class ArraySet extends Set<any> {
override add(arr: any): any {
super.add(arr.toString());
}
override has(arr): boolean {
return super.has(arr.toString());
}
}
is there a way to edit this class in order to get values as array??
Currently:
const set = new ArraySet()
set.add([1,1])
set.add([2,1])
set.forEach(e => console.log(typeof(e)))
# string
# string
Expected:
const set = new ArraySet()
set.add([1,1])
set.add([2,1])
set.forEach(e => console.log(typeof(e)))
# object # because I want the element to be the array
# object
combining a few of the suggestions you could maybe get away with not needing to override the iterator part and simply controlling what goes inside the set like so
class ArrayNumberSet extends Set<number[]> {
private readonly keyMap: Map<string, number[]> = new Map();
private key(value: number[]): string {
return JSON.stringify(value);// or value.toString()
}
override add(value: number[]): this {
const key = this.key(value);
const old = this.keyMap.get(key);
if (old) {
this.delete(old);
}
this.keyMap.set(key, value);
super.add(value);
return this;
}
override clear(): void {
this.keyMap.clear();
super.clear();
}
override delete(value: number[]): boolean {
const key = this.key(value);
const old = this.keyMap.get(key);
if (old) {
this.keyMap.delete(key);
return super.delete(old);
}
return false
}
override has(value: number[]): boolean {
return this.keyMap.has(this.key(value))
}
}
this would treat [1, 2], [2, 1], [2, 1, 1] as different objects. If you don't want that, consider a set of sets maybe or build a key from sorted arrays