I have a very long string and I need a unique ID to cache it. The id doesn't need to be reversed however equal strings need to return the equal id.
For example:
I don't need to reverse the hash.
What's the best way to achieve this with Javascript?
The shorter the hash, the higher the chances of collision.
However, in the Java world, there is a string hashCode helper that returns a "not so unique" integer out of a string, and it's the smallest way to map a string as ID, but it doesn't guarantee uniqueness and it suffers collisions.
Accordingly, I strongly discourage you to use this in the wild, but for answer sake, here how you can play around with such hash:
function hashCode(s) {
for (var h = 0, i = 0; i < s.length; h &= h)
h = 31 * h + s.charCodeAt(i++);
return h;
}
On the other hand, sha256 is a one way hashing that "doesn't suffer collisions" (it does, but much less than MD5, SHA1, or the hashCode up there), so while the result is a longer unique id, it's kinda granted to always work as expected, and it's explained in MDN.
P.S. NodeJS 15+ has a crypto.webcrypto namespace that is identical to the Web one, so you can use the same code in browsers and server.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With