Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

185
Views
How to overwrite Javascript / Typescript Set iterator or values?

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
almost 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

almost 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!