- 
      
- 
        Save tnhu/d293b0382b5a2c4a561b to your computer and use it in GitHub Desktop. 
    Shortest JavaScript String Hash implementation
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | // 32 bit FNV-1a hash | |
| // Ref.: http://isthe.com/chongo/tech/comp/fnv/ | |
| function fnv32a(str) { | |
| var FNV1_32A_INIT = 0x811c9dc5, | |
| hval = FNV1_32A_INIT, | |
| i, len; | |
| for (i = 0, len = str.length; i < len; i++) { | |
| hval ^= str.charCodeAt(i); | |
| hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24); | |
| } | |
| return hval >>> 0; | |
| } | |
| // Hex http://engineering.chartbeat.com/2014/08/13/you-dont-know-jack-about-hashing/ | |
| function fnv32h(str) { | |
| var h = [0x6295c58d, 0x62b82175, 0x07bb0142, 0x6c62272e]; | |
| for (var i = 0, len = str.lenth; i < len; i++) { | |
| h[i % 4] ^= str.charCodeAt(i); | |
| h[i % 4] *= 0x01000193; | |
| } | |
| /* returns 4 concatenated hex representations */ | |
| return h[0].toString(16) + h[1].toString(16) + h[2].toString(16) + h[3].toString(16); | |
| } | |
| console.log(fnv32a('abc')); // 440920331 | |
| console.log(fnv32a('abc').toString(2)); // 11010010001111110100100001011 | |
| console.log(fnv32a('abc').toString(4)); // 122101332210023 | |
| console.log(fnv32a('abc').toString(8)); // 3221764413 | |
| console.log(fnv32a('abc').toString(16)); // 1a47e90b | |
| console.log(fnv32a('abc').toString(32)); // d4fq8b | |
| console.log(fnv32a('abc').toString(36)); // 7aigaz | |
| console.log(fnv32h('abc')); // 6295c58d62b821757bb01426c62272e | |
| (1234567890).toString(36) // => "kf12oi" | |
| parseInt("kf12oi",36) // => 1234567890 | |
| // Good read: http://programmers.stackexchange.com/questions/49550/which-hashing-algorithm-is-best-for-uniqueness-and-speed | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment