Why does Javascript Set not do unique objects?

Based on Joe Yichong post, here a suggestion to extend Set for TypeScript.

export class DeepSet extends Set {

  add (o: any) {
    for (let i of this)
      if (this.deepCompare(o, i))
        return this;
    super.add.call(this, o);
    return this;
  };

  private deepCompare(o: any, i: any) {
    return JSON.stringify(o) === JSON.stringify(i)
  }
}


well, if you are looking for a deep unique set, you can make a deep set by youself, by extending the original 'Set', like this:

function DeepSet() {
    //
}
DeepSet.prototype = Object.create(Set.prototype);
DeepSet.prototype.constructor = DeepSet;
DeepSet.prototype.add = function(o) {
    for (let i of this)
        if (deepCompare(o, i))
            throw "Already existed";
    Set.prototype.add.call(this, o);
};

Another option is you could use JSON.stringify() to keep your object unique, that way it is comparing against a string instead of an object reference.

set.add(JSON.stringify({name:'a', value: 'b'}))

and then after everything is formatted you can just parse those lines back to an array like this:

const formattedSet = [...set].map(item) => {
  if (typeof item === 'string') return JSON.parse(item);
  else if (typeof item === 'object') return item;
});

Tags:

Javascript