javascripthashmd5sha1

Simple (non-secure) hash function for JavaScript?


Possible Duplicate:
Generate a Hash from string in Javascript/jQuery

Can anyone suggest a simple (i.e. tens of lines of code, not hundreds of lines) hash function written in (browser-compatible) JavaScript? Ideally I'd like something that, when passed a string as input, produces something similar to the 32 character hexadecimal string that's the typical output of MD5, SHA1, etc. It doesn't have to be cryptographically secure, just reasonably resistant to collisions. (My initial use case is URLs, but I'll probably want to use it on other strings in the future.)


Solution

  • I didn't verify this myself, but you can look at this JavaScript implementation of Java's String.hashCode() method. Seems reasonably short.

    It has been long accepted that modifying built-in prototypes is bad practice, so use a plain function like this:

    /**
     * Returns a hash code from a string
     * @param  {String} str The string to hash.
     * @return {Number}    A 32bit integer
     * @see http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
     */
    function hashCode(str) {
        let hash = 0;
        for (let i = 0, len = str.length; i < len; i++) {
            let chr = str.charCodeAt(i);
            hash = (hash << 5) - hash + chr;
            hash |= 0; // Convert to 32bit integer
        }
        return hash;
    }