2

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;
};
prasun
  • 7,073
  • 9
  • 41
  • 59
07_05_GuyT
  • 2,787
  • 14
  • 43
  • 88
  • The JSFiddle doesn't work. – Yaron Nov 09 '15 at 09:21
  • I dont think this implementation can be easily changed to constant length hash for any input, but you can always pad it with '0' in front + cut what's too long and keep constant length therefore :) However Im not sure if it will work for very long strings anyway. – mikus Nov 09 '15 at 09:23
  • @mikus - this is good point with the leading zero can you please update the jsBin since this could be an answer!many thanks – 07_05_GuyT Nov 09 '15 at 09:29
  • see the answer below :) – mikus Nov 09 '15 at 11:08

1 Answers1

3

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)); 
Community
  • 1
  • 1
mikus
  • 3,042
  • 1
  • 30
  • 40