0

In this topic : Simplest way to merge ES6 Maps/Sets?

I found a nice way to merge Set or Map

let set3 = new Set(function*() { yield* set1; yield* set2; }());

I would like to make a function that can merge any number of Sets like so :

function  mergeSets() { 
    return new Set(function*() {
        for (const set of arguments) {
            yield* set
        }
    }())
}

I there a way to ? When i test this one i get an empty Set as result

BastienSander
  • 1,718
  • 4
  • 24
  • 50

1 Answers1

1

You're using your arguments inside the inner function*, which is immediately invoked without arguments, so the arguments are empty, so iterating over it results in the returned set being empty. I would use parameter rest syntax instead, in the outer function, to collect the arguments into a proper array, and then you can iterate over the array:

(Open your browser console, not the snippet console, to see the resulting Set:)

const set1 = new Set(['1', '2', '3']);
const set2 = new Set(['4', '5', '6']);
const set3 = new Set(['7', '8', '9']);

const mergeSets = (...sets) => new Set(function* () {
  for (const set of sets) yield* set;
}());

console.log(
  mergeSets(set1, set2, set3)
);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320