07_05_GuyT
07_05_GuyT

Reputation: 2887

How to limit the hash length

Im need to use this hash algorithm but my question is wheater I can put constant length to it? I need it to be with length 6 or 7 characters and sometimes its bigger and sometimes its smaller ...

https://jsfiddle.net/14fmwvyn/

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;
};

Upvotes: 2

Views: 1992

Answers (1)

mikus
mikus

Reputation: 3215

I'd generally stick to known hashing methods and its best to use an algorithm that can enforce constant length by itself, but still, hash is hash, as long as it's same for same values it's fine, otherwise it might be only inefficient.

Therefore one simple way that will always work is to cut off the trailing part above the desirable length, and pad the strings that are too short. About padding you can read here:

Adding extra zeros in front of a number using jQuery?

shortening you can do with simple str.substr call, please see the updated fiddle below for an exmaple. You might need to work on negatives handling. Also I am not sure if you hash will work properly with super long strings, but the general machanism stays the same.

https://jsfiddle.net/14fmwvyn/4/

var mystring = "t7";      //some text string

function pad (str, max) {  //this will add '0' to 'smaller' numbers
  str = str.toString();
  return str.length < max ? pad("0" + str, max) : str;
}

//your method untouched
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;
};

var hash_length =7;     //constant hash length, 
var hashCode = mystring.hashCode(); 
//padded with '0's if too short
var padded = pad(hashCode, hash_length);    
//trimmed if too long
var trimmed = hashCode.toString().substr(0,hash_length);    
//padded and trimmed if too long
var trimmedAndPadded = pad(hashCode.toString().substr(0,hash_length), hash_length)); 

Upvotes: 3

Related Questions