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.