0

I've got a function like this:

var hashString = function (str) {
            var mask = '';
            if (str.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
            if (str.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            if (str.indexOf('#') > -1) mask += '0123456789';
            if (str.indexOf('!') > -1) mask += '~`!@#$%^&*()_+-={}[]:";\'<>?,./|\\';
            var result = '';
            for (var i = 8; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)];
            return result;
        }

How do I make it return always the same hash for a particular string?

Aga
  • 1
  • 1
  • Im not a master of hashing algorithms, but I would say that random part should make it always different( most of the case). Am I right? – GarbageCollector Jan 14 '17 at 11:12

1 Answers1

0

This function will always return the same hash for a particular string:

 /**
 * Calculate a 32 bit FNV-1a hash
 * Found here: https://gist.github.com/vaiorabbit/5657561
 * Ref.: http://isthe.com/chongo/tech/comp/fnv/
 *
 * @param {string} str the input value
 * @param {boolean} [asString=false] set to true to return the hash value as 
 *     8-digit hex string instead of an integer
 * @param {integer} [seed] optionally pass the hash of the previous chunk
 * @returns {integer | string}
 */
function hashFnv32a(str, asString, seed) {
    /*jshint bitwise:false */
    var i, l,
        hval = (seed === undefined) ? 0x811c9dc5 : seed;

    for (i = 0, l = str.length; i < l; i++) {
        hval ^= str.charCodeAt(i);
        hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
    }
    if (asString) {
        // Convert to 8 digit hex string
        return ("0000000" + (hval >>> 0).toString(16)).substr(-8);
    }
    return hval >>> 0;
}

Generate a Hash from string in Javascript/jQuery

Community
  • 1
  • 1
Yichong
  • 707
  • 4
  • 10
  • Thanks very much for this, but the hash is supposed to consist of letters, not digits, I forgot to specify this... – Aga Jan 14 '17 at 12:10