In JavaScript, I have the following Sets:
var mySet = new Set(["foo", "bar", "baz"]);
var valuesToRemove = new Set(["foo", "baz"]);
I need a function that removes a set of values:
removeAll(mySet, valuesToRemove);
// expected value of mySet: Set ["bar"]
// or a function that returns a new Set
var myNewSet = removeAll(mySet, valuesToRemove);
// expected value of myNewSet: Set ["bar"]
Question: Does any ES6-modules-compatible library exists that does the trick?
Lodash has a similar function for Arrays, but supporting JavaScript builtin iterable is tagged as wontfix
. And I prefer to avoid doing multiple Array↔Set/Set↔Array conversions.
Alternatively, I will write my own function.
It is much easier to write your own function than use a library for a single lightweight functionality:
var mySet = new Set(["foo", "bar", "baz"]);
var valuesToRemove = new Set(["foo", "baz"]);
function removeAll(originalSet, toBeRemovedSet) {
[...toBeRemovedSet].forEach(function(v) {
originalSet.delete(v);
});
}
console.log([...mySet]);
removeAll(mySet, valuesToRemove);
console.log([...mySet]);
I have used ES6 syntax since you use ES6, according to your question.
You can this function in a static class like SetUtility
for your convenience.
You could use Set#forEach
directly with the set and delete then the value from the other set.
var mySet = new Set(["foo", "bar", "baz"]);
var valuesToRemove = new Set(["foo", "baz"]);
function removeAll(originalSet, toBeRemovedSet) {
toBeRemovedSet.forEach(Set.prototype.delete, originalSet);
}
console.log([...mySet]);
removeAll(mySet, valuesToRemove);
console.log([...mySet]);
You can use for..of
loop .delete()
var removeAll = (keys, arr) => {for (prop of keys) arr.delete(prop); return arr};
removeAll(valuesToRemove, mySet); // `Set [ "bar" ]`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With