Is there any kind of hash code function in JavaScript?

后端 未结 20 1168
慢半拍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.

    0 讨论(0)
  • 2020-12-04 10:43

    Just use hidden secret property with the defineProperty enumerable: false

    It work very fast:

    • The first read uniqueId: 1,257,500 ops/s
    • All others: 309,226,485 ops/s
    var nextObjectId = 1
    function getNextObjectId() {
        return nextObjectId++
    }
    
    var UNIQUE_ID_PROPERTY_NAME = '458d576952bc489ab45e98ac7f296fd9'
    function getObjectUniqueId(object) {
        if (object == null) {
            return null
        }
    
        var id = object[UNIQUE_ID_PROPERTY_NAME]
    
        if (id != null) {
            return id
        }
    
        if (Object.isFrozen(object)) {
            return null
        }
    
        var uniqueId = getNextObjectId()
        Object.defineProperty(object, UNIQUE_ID_PROPERTY_NAME, {
            enumerable: false,
            configurable: false,
            writable: false,
            value: uniqueId,
        })
    
        return uniqueId
    }
    
    0 讨论(0)
提交回复
热议问题