Set
and Map
have slightly different APIs in terms of their stored values. While Set
s contain values only, Map
s contain their associated keys as well.
Because of this, should both of the structures have filter
, map
, forEach
,... functions just like Array
does, the action setting presumtion about each iterated value is likely to be slightly different, specifically:
Map: function(key, value) { }
Set: function(value) { }
Because when you already keep keys in a Map
it makes sense to be able to inspect the value of the key
during iteration as well.
Now if you encountered a situation where you would like to iterate over any of the two collections but cared only about the value, you would need two functions, one for each data collection.
map.forEach((key, value) => console.log(value));
set.forEach(value => console.log(value));
Even though you only care about the value and the logic of both actions is clearly the same, you cannot write a function to serve both collections. The entries
method of both Set
and Map
fixes this issue by providing a common interface.
By creating the following function (or its alternative, I am not manily a JS developer so please excuse any inaccuracies):
function forEach(entriesIterator, action) {
let current = entriesIterator.next();
while (current.done === false) {
action(current.value[1]);
current = entriesIterator.next();
}
}
you can feed either entries
of Map
and/or Set
and it will still work.
forEach(map.entries(), value => console.log(value));
forEach(set.entries(), value => console.log(value));
TLDR: The entries
method provides an abstraction to iterate over a data collection where you may potentially only care about the values.