Is there hash code function accepting any object type?

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

function hashCode(string){
    var hash = 0;
    for (var i = 0; i < string.length; i++) {
        var code = string.charCodeAt(i);
        hash = ((hash<<5)-hash)+code;
        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.

Leave a Comment