Synopsis
Modify the the add method on Set and Weakset so it is capable of adding more than one element by accepting multiple arguments. Similar to Array.prototype.push.
Motivation
The goal here is to simplify the logic needed when attempting to merge one or more iterables of unknown size into a Set or WeakSet. Right now the only way of doing this is by looping through each iterable and calling the "add" method on the main
Today Example
const mutableSet = new Set([1, 2, 3]);
const setA = new Set([3, 4, 5]);
const array = [4, 5, 6, 7];
// This or a for loop
setA.forEach(item => mutableSet.add(item));
array.forEach(item => mutableSet.add(item));
console.log(mutableSet);
// output: Set(7) {1, 2, 3, 4, 5, 6, 7}
Proposal Example
const mutableSet = new Set([1, 2, 3]);
const setA = new Set([3, 4, 5]);
const array = [4, 5, 6, 7];
mutableSet.add(...setB, ...array);
console.log(mutableSet);
// output: Set(7) {1, 2, 3, 4, 5, 6, 7}
Rough Polyfill Example
;(() => {
if (Set) {
const add = Set.prototype.add;
Set.prototype.add = function (...args) {
args.forEach(arg => add.call(this, arg))
return this;
}
}
if (WeakSet) {
const add = WeakSet.prototype.add;
WeakSet.prototype.add = function (...args) {
args.forEach(arg => add.call(this, arg))
return this;
}
}
})();