Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make short hash from long string [duplicate]

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:

  • this-is-a-very-long-string -> SFG2527G
  • this-is-something-else -> JSNTFK2783
  • this-is-a-very-long-string -> SFG2527G

I don't need to reverse the hash.

What's the best way to achieve this with Javascript?

like image 902
Costantin Avatar asked Jun 18 '26 17:06

Costantin


1 Answers

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.

like image 111
Andrea Giammarchi Avatar answered Jun 20 '26 08:06

Andrea Giammarchi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!