Is there any kind of hash code function in JavaScript?

后端 未结 20 1179
慢半拍i
慢半拍i 2020-12-04 09:59

Basically, I\'m trying to create an object of unique objects, a set. I had the brilliant idea of just using a JavaScript object with objects for the property names. Such as,

20条回答
  •  伪装坚强ぢ
    2020-12-04 10:41

    If you want a hashCode() function like Java's in JavaScript, that is yours:

    String.prototype.hashCode = function(){
        var hash = 0;
        for (var i = 0; i < this.length; i++) {
            var character = this.charCodeAt(i);
            hash = ((hash<<5)-hash)+character;
            hash = hash & hash; // Convert to 32bit integer
        }
        return hash;
    }
    

    That is the way of implementation in Java (bitwise operator).

    Please note that hashCode could be positive and negative, and that's normal, see HashCode giving negative values. So, you could consider to use Math.abs() along with this function.

提交回复
热议问题