Just a heads up: For those who are wondering, I am fully aware that adding methods to JavaScript built-in objects is generally considered to be a bad practice.
However, I'm currently in the process of adding a new method to the array prototype for a small personal 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));
};
Upon trying to use the new method, the first push works as expected. However, on the second call, the "array before:" log displays correctly with the initial push being part of the array. Unfortunately, when I pass the array to my Set constructor, it results in an empty set, which is evident from both the "set before:" and "set after:" logs showing an empty {}
. I'm not sure why the Set won't be instantiated from the array. Any assistance would be greatly appreciated.