Is there any kind of hash code function in JavaScript?

后端 未结 20 1204
慢半拍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条回答
  •  旧时难觅i
    2020-12-04 10:23

    If you want to use objects as keys you need to overwrite their toString Method, as some already mentioned here. The hash functions that were used are all fine, but they only work for the same objects not for equal objects.

    I've written a small library that creates hashes from objects, which you can easily use for this purpose. The objects can even have a different order, the hashes will be the same. Internally you can use different types for your hash (djb2, md5, sha1, sha256, sha512, ripemd160).

    Here is a small example from the documentation:

    var hash = require('es-hash');
    
    // Save data in an object with an object as a key
    Object.prototype.toString = function () {
        return '[object Object #'+hash(this)+']';
    }
    
    var foo = {};
    
    foo[{bar: 'foo'}] = 'foo';
    
    /*
     * Output:
     *  foo
     *  undefined
     */
    console.log(foo[{bar: 'foo'}]);
    console.log(foo[{}]);
    

    The package can be used either in browser and in Node-Js.

    Repository: https://bitbucket.org/tehrengruber/es-js-hash

提交回复
热议问题