Why the Sets have keys equals to values?

2019-08-24 13:51发布

The book

Understanding ECMAScript 6

states that

Sets don’t have keys, however. The people behind the ECMAScript 6 standard could have made the callback function in the set version of forEach() accept two arguments, but that would have made it different from the other two. Instead, they found a way to keep the callback function the same and accept three arguments: each value in a set is considered to be the key and the value. As such, the frst and second argument are always the same in forEach() on sets to keep this functionality consistent with the other forEach() methods on arrays and maps.

why not to make keys as in Arrays?
what is a motive behind that?

1条回答
劳资没心,怎么记你
2楼-- · 2019-08-24 14:25

In some sense, Sets actually do have indices, if not keys..

Logically, a set would not even have a defined iteration order, never mind keys. But the fact is, iteration of new Set([1, 2, 3]) is ordered differently from new Set([3, 1, 2]).

This is the difference between mathematics and programming.


Update: Question updated with discussion from comments


The key/index really shouldn't exist. If there was a reasonable way to avoid even having it, I think they would have. But in programming we can't just say "for all s in set S..." We need to be able to iterate over those s's. But we shouldn't look for any more than this iteration. As much as possible, new Set([1, 2, 3]) and new Set([3, 1, 2]) should act as much alike as possible.

Imagine if we serialized a Trie to store the set {'baby', 'bad', 'bank', 'box', 'dad', 'dance'} as (b(a(b(y)dn(k))o(x))d(a(dn(c(e))))). That has no indices at all. The only reason that these are supplied is to keep forEach as consistent as possible across the various types. Set doesn't fit as well as others. That's all.

In other words, it makes more sense to reuse the value (or alternatively to consistently pass some irrelevant token) than to pretend the iteration indices are meaningful parts of the Set interface. Ordering is accidental, implementation details, necessary since programmers cannot use mathematical techniques. But it is not part of the essential interface of Sets.

查看更多
登录 后发表回答