Advertisement
rg443

hash: String.hashCode(), djb2, sdbm, lose lose

Nov 24th, 2013
487
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Java String.hashCode() */
  2. hashCode = function(str){
  3.     var hash = 0;
  4.     if (str.length == 0) return hash;
  5.     for (i = 0; i < str.length; i++) {
  6.         char = str.charCodeAt(i);
  7.         hash = ((hash<<5)-hash)+char;
  8.         hash = hash & hash; // Convert to 32bit integer
  9.     }
  10.     return hash>>>0;
  11. }
  12.  
  13. /* djb2 */
  14. djb2Code = function(str){
  15.     var hash = 5381;
  16.     for (i = 0; i < str.length; i++) {
  17.         char = str.charCodeAt(i);
  18.         hash = ((hash << 5) + hash) + char; /* hash * 33 + c */
  19.     }
  20.     return hash>>>0;;
  21. }
  22.  
  23.  
  24. /* sdbm */
  25. sdbmCode = function(str){
  26.     var hash = 0;
  27.     for (i = 0; i < str.length; i++) {
  28.         char = str.charCodeAt(i);
  29.         hash = char + (hash << 6) + (hash << 16) - hash;
  30.     }
  31.     return hash>>>0;
  32. }
  33.  
  34. /* lose lose */
  35. loseCode = function(str){
  36.     var hash = 0;
  37.     for (i = 0; i < str.length; i++) {
  38.         char = str.charCodeAt(i);
  39.         hash += char;
  40.     }
  41.     return hash;
  42. }
  43.  
  44. /* sdbm prototype */
  45. String.prototype.sdbmCode = function(){
  46.         var hash = 0;
  47.         var tempChar;
  48.     for (var i = 0; i < this.length; i++) {
  49.         tempChar = this.charCodeAt(i);
  50.         hash = tempChar + (hash << 6) + (hash << 16) - hash;
  51.     }
  52.     return hash>>>0;
  53. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement