Is there any kind of hash code function in JavaScript?

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

    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
    }
    

提交回复
热议问题