'How can I convert Map to Set and vice versa?

forEach() method uses value variable twice. It's written that this is done in order to ensure the compatibility of Map and Set.

Source

That’s for compatibility with Map where the callback passed forEach has three arguments. Looks a bit strange, for sure. But may help to replace Map with Set in certain cases with ease, and vice versa.

let set = new Set(["orange", "apple", "banana"]);

set.forEach((value, valueAgain, set) => {
  console.log(valueAgain); //"orange", "apple", "banana"
});

So, my question is how Set can convert into Set and vice versa? As I understand, there is no special method for this case.



Solution 1:[1]

The point is not that you can easily replace a set with a map in your code. If you do that, you touch the code anyway, and would have no trouble also rewriting the iteration.

The real benefit is that it allows writing code that can handle both at once. In your example:

function print(collection) {
    collection.forEach((value, key) => {
        console.log(key, value);
    });
}

const set = new Set(["orange", "apple", "banana"]);
const map = new Map([[1, "peach"], [2, "pear"]]);

print(set); // works
print(map); // works the same

Solution 2:[2]

It does not say anything about conversion. It says that you can use the same function callback for the Map and the Set.

const set = new Set(["oranges", "apples", "bananas"]);
const map = new Map([
  ['cucumber', 500],
  ['tomatoes', 350],
  ['onion',    50]
]);
const print = (value, key) => console.log(value, key);
set.forEach(print)
// oranges oranges
// apples apples
// bananas bananas
map.forEach(print)
// 500 cucumber
// 350 tomatoes
// 50 onion

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bergi
Solution 2 Konrad Linkowski