javascript的hashCode函數實現代碼小結
為了使用的方便,稍稍再改良了一下
function hashcode(str) { var hash = 0, i, chr, len; if (str.length === 0) return hash; for (i = 0, len = str.length; i < len; i++) { chr = str.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash;}hashcode('this is a string')//-1853110172
這里接受的參數是一個 String,其它類型怎么辦?可以先做一個統一的處理,比如
hashcode(JSON.stringify(obj))序列化之后再使用 hashCode 函數,基本所有類型數據都通吃,除了含有循環嵌套的對象。
PS:函數實現中有一行使用了 “|” 運算符,只是利用 Bitwise 運算符轉換參數為 32bit,用來確保結果是個 32位整數。
這里是Java的直接替代品字符串.hashCode()用Javascript實現的方法。
我編寫這個函數是為了滿足工作中的一個需求。顯然,后端工程師認為hashCode()是一個標準函數。這個項目的一個障礙不僅是如何翻譯Java中用來生成hashCode()的數學公式,還包括如何強制Javascript使用32位整數數學(這不是一個小的壯舉)。
幸運的是,我發現Java支持位運算符,這些運算符被限制在32位整數數學中。
下面是Javascript生成的字符串原型。使用這個原型,您可以簡單地對任何字符串調用.hashCode(),例如“some string”.hashCode(),并接收一個數字哈希代碼(更具體地說,是一個Java等效代碼),如1395333309。
String.prototype.hashCode = function(){var hash = 0;if (this.length == 0) return hash;for (i = 0; i < this.length; i++) {char = this.charCodeAt(i);hash = ((hash<<5)-hash)+char;hash = hash & hash; // Convert to 32bit integer}return hash;}
下面是其它網友的補充
hashCode = function(str){ var hash = 0; if (str.length == 0) return hash; for (i = 0; i < str.length; i++) { char = str.charCodeAt(i); hash = ((hash<<5)-hash)+char; hash = hash & hash; // Convert to 32bit integer } return hash;}djb2Code = function(str){ var hash = 5381; for (i = 0; i < str.length; i++) { char = str.charCodeAt(i); hash = ((hash << 5) + hash) + char; /* hash * 33 + c */ } return hash;}sdbmCode = function(str){ var hash = 0; for (i = 0; i < str.length; i++) { char = str.charCodeAt(i); hash = char + (hash << 6) + (hash << 16) - hash; } return hash;}loseCode = function(str){ var hash = 0; for (i = 0; i < str.length; i++) { char = str.charCodeAt(i); hash += char; } return hash;}
以上就是javascript的hashCode函數實現代碼小結的詳細內容,更多關于javascript hashCode的資料請關注好吧啦網其它相關文章!
相關文章: