Hacker News new | past | comments | ask | show | jobs | submit login

As you suspected, the random ID is just for objects and arrays, which are mapped by identity rather than contents. Strings are hashed by content.

(You can't do it by address, since everything is movable by the garbage collector. With a non-copying collector, you could just use the address.)




OK I guess that makes sense... I find it odd that such a random number is called a "hash code". I guess because it's an implementation detail and not exposed to the user?

When I think of user-facing hash tables, I think that the keys must respect object equality (and sometimes equality can be implemented with identity, for singletons).

But I guess JavaScript has no concept of user-definable hash functions for objects, like Python and Java do? So this is purely an implementation detail?

You can extend my example to something like:

    var s1 = readWholeFile('file.txt')
    var s2 = readWholeFile('file.txt')
   
    var array1 = [0, s1]
    var array2 = [0, s2]
    
    var d = {}
    d[array1] = 'xyz'
    print(d[array2])
Hm I just tried this and I noticed that JavaScript decays the array1 key to a string!!! That is really bad.

But I guess there is some logic to it, because hashing with mutable keys isn't exposed to the user. Because it doesn't make sense!

But in many languages, if array1 and array2 are hashable, then they should retrieve the same value, even though they are not identical objects.

So their hash codes can't be random numbers -- they should be derived from their values. Overall I find this whole discussion pretty confusing :)


> When I think of user-facing hash tables, I think that the keys must respect object equality (and sometimes equality can be implemented with identity, for singletons).

It's hard to respect object equality when the language itself doesn't have consistent notions of what equality actually is.


The {} object uses only strings as keys. You need to use:

  var d = new Map();
  d.set(array1, 'xyz');
  print(d.get(array2));
(Map is new in ES2015, but Node and all the browsers have it now).




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: