5 ms·
Javascript taught me to never assume any ordering in a dict/map/hashmap (whatever the term)
by dmitriid 7y ago
Javascript taught me to never assume any ordering in a dict/map/hashmap (whatever the term)
- pfdietz 7y agoIs the ordering there at least fixed, or can it vary from run to run even on the same data, or between implementations or versions of the same implementation? EDIT: to clarify, I was asking about JavaScript there.
- deleted 7y ago[deleted]
- nobleach 7y agoIt is deterministic, but it's an odd rule-set. For example: `var o = { 3: 'foo', 1: 'bar', b: 'baz', a: 'quux' }` Will yield: `{1: "bar", 3: "foo", b: "baz", a: "quux"}`. Numeric keys get sorted. String keys are insertion-order. If key order is a priority, a Map should be used instead. Often when JavaScript's objects are used and a particular sort order is required, an accompanying (sorted) array is used.
- deleted 7y ago[deleted]
- blattimwind 7y agoIf the ordering is determined by a hash function and it's always the same it is likely a defect in the implementation, because keys can be easily chosen to cause massive performance degredation; essentially a DoS attack. That's why many dynamic languages these days use things like siphash with a random key.
- pfdietz 7y agoI'll argue that having the order depend on the hash function, rather than insertion order, is the problem. It's bad to have unnecessary nondeterminism in software. It makes testing and reproducing bugs unnecessarily difficult.
- Leszek 7y agoWell, JavaScript Map preserves insertion order when iterating entries, and as of ES2015 (i.e. ES6), for-in also iterates the (string, non-numeric) properties of an object in insertion order.
- _verandaguy 7y agoThat's fine, as long as you adjust your assumptions when working with other languages.
- thrower123 7y agoIt's a safe default, if maybe not a performant one.
- theli0nheart 7y agoHolding as little assumptions as possible works as a general rule no matter which language you're using.
- deleted 7y ago[deleted]
- threatofrain 7y agoThese collections are often default defined as unordered collections; it’s just that people discovered over time that some were iterable even if the language docs said otherwise.
- tremon 7y agoI don't think ordering and iteration are related, are they? Whether something is sortable has no impact on whether it is enumerable.
- threatofrain 7y agoHow I think about it is if something is unordered then the iteration strategy is a question.
- Sean1708 7y agoWhat would it even mean for a container to be ordered if you can't iterate through it?