Javascript generate unique number based on string

How about this:

String.prototype.hashCode = function() {
  var hash = 0, i, chr, len;
  if (this.length === 0) return hash;
  for (i = 0, len = this.length; i < len; i++) {
    chr   = this.charCodeAt(i);
    hash  = ((hash << 5) - hash) + chr;
    hash |= 0; // Convert to 32bit integer
  }
  return hash;
};

You want a hash function. Hash functions are generally not unique (as in, there are collisions), but the keyspace is so vast that you might live entire lifetimes without finding one in your app.

Look for SHA1 and SHA256 implementations for JavaScript for a start, if you're using node, look at the crypto module.

Tags:

Javascript