1

Disclaimer: This is for learning purposes, and I already know adding methods to js built-in objects is not a good practice.

I'm trying to add a new method to the array prototype for a small hobby project:

    Array.prototype.add = function (element) {
      console.log('array before: ' + JSON.stringify(this));
      let arr = this;
      if (arr.length) {
        let set = new Set(arr);
        console.log('set before: ' + JSON.stringify(set));
        console.log('adding element: ' + JSON.stringify(element));
        set = set.add(element);
        console.log('set after: ' + JSON.stringify(set));
      } else {
        arr.push(element);
      }
      console.log('array after: ' + JSON.stringify(arr));
    };

On attempting to call the new method once it pushes as expected. On a consecutive call the "array before:" log prints as expected with the first push making up the contents of the array, but feeding the array to my Set constructor results in an empty set, as evidenced by my "set before:" and "set after:" logs both printing an empty {}. I'm unsure why the Set won't instantiate from the array, any help would be appreciated.

1 Answers1

1

JSON.stringify always results in an empty object for sets

var s = new Set([1,2,3]);
console.log(s.size);
console.log(JSON.stringify(s));

Sets don't have properties that can be serialized. In other words, you are using the wrong method to verify whether the set is empty and are jumping to the wrong conclusion. Log set.size instead, or just set itself.

Related: JSON stringify a Set

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • This insight allowed me to see my real mistake and move forward. If I had just kept writing out my code and included the steps where I convert back to an array and return I would have been fine. Thank you! – Aaron James Mccoy Jun 14 '17 at 13:31