Is there any kind of hash code function in JavaScript?

后端 未结 20 1185
慢半拍i
慢半拍i 2020-12-04 09:59

Basically, I\'m trying to create an object of unique objects, a set. I had the brilliant idea of just using a JavaScript object with objects for the property names. Such as,

20条回答
  •  旧巷少年郎
    2020-12-04 10:31

    I will try to go a little deeper than other answers.

    Even if JS had better hashing support it would not magically hash everything perfectly, in many cases you will have to define your own hash function. For example Java has good hashing support, but you still have to think and do some work.

    One problem is with the term hash/hashcode ... there is cryptographic hashing and non-cryptographic hashing. The other problem, is you have to understand why hashing is useful and how it works.

    When we talk about hashing in JavaScript or Java most of the time we are talking about non-cryptographic hashing, usually about hashing for hashmap/hashtable (unless we are working on authentication or passwords, which you could be doing server-side using NodeJS ...).

    It depends on what data you have and what you want to achieve.

    Your data has some natural "simple" uniqueness:

    • The hash of an integer is ... the integer, as it is unique, lucky you !
    • The hash of a string ... it depends on the string, if the string represents a unique identifier, you may consider it as a hash (so no hashing needed).
    • Anything which is indirectly pretty much a unique integer is the simplest case
    • This will respect: hashcode equal if objects are equal

    Your data has some natural "composite" uniqueness:

    • For example with a person object, you may compute a hash using firstname, lastname, birthdate, ... see how Java does it: Good Hash Function for Strings, or use some other ID info that is cheap and unique enough for your usecase

    You have no idea what your data will be:

    • Good luck ... you could serialize to string and hash it Java style, but that may be expensive if the string is large and it will not avoid collisions as well as say the hash of an integer (self).

    There is no magically efficient hashing technique for unknown data, in some cases it is quite easy, in other cases you may have to think twice. So even if JavaScript/ECMAScript adds more support, there is no magic language solution for this problem.

    In practice you need two things: enough uniqueness, enough speed

    In addition to that it is great to have: "hashcode equal if objects are equal"

    • https://en.wikipedia.org/wiki/Hash_table#Collision_resolution
    • Relationship between hashCode and equals method in Java

提交回复
热议问题