Is there any kind of hash code function in JavaScript?

后端 未结 20 1191
慢半拍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:43

    If you want to have unique values in a lookup object you can do something like this:

    Creating a lookup object

    var lookup = {};
    

    Setting up the hashcode function

    function getHashCode(obj) {
        var hashCode = '';
        if (typeof obj !== 'object')
            return hashCode + obj;
        for (var prop in obj) // No hasOwnProperty needed
            hashCode += prop + getHashCode(obj[prop]); // Add key + value to the result string
        return hashCode;
    }
    

    Object

    var key = getHashCode({ 1: 3, 3: 7 });
    // key = '1337'
    lookup[key] = true;
    

    Array

    var key = getHashCode([1, 3, 3, 7]);
    // key = '01132337'
    lookup[key] = true;
    

    Other types

    var key = getHashCode('StackOverflow');
    // key = 'StackOverflow'
    lookup[key] = true;
    

    Final result

    { 1337: true, 01132337: true, StackOverflow: true }

    Do note that getHashCode doesn't return any value when the object or array is empty

    getHashCode([{},{},{}]);
    // '012'
    getHashCode([[],[],[]]);
    // '012'
    

    This is similar to @ijmacd solution only getHashCode doesn't has the JSON dependency.

提交回复
热议问题