How do the ES6 Map shims work

后端 未结 3 1338
不知归路
不知归路 2021-02-13 07:24

Based on my understanding of the docs (here and here) one would need a reference to the memory address for it to work:

const foo = {};
const map = new Map();
ma         


        
3条回答
  •  臣服心动
    2021-02-13 07:56

    The trick is to store in an array and perform the lookup in O(n) time by iterating and using strict comparison—instead of using a true hash function which would be O(1) lookup. For example consider this:

    var myObj = {};
    
    var someArray = [{}, {}, myObj, {}];
    
    console.log(someArray.indexOf(myObj)); // returns 2
    

    Here is my implementation from another answer: Javascript HashTable use Object key

    function Map() {
        var keys = [], values = [];
    
        return {
            put: function (key, value) {
                var index = keys.indexOf(key);
                if(index == -1) {
                    keys.push(key);
                    values.push(value);
                }
                else {
                    values[index] = value;
                }
            },
            get: function (key) {
                return values[keys.indexOf(key)];
            }
        };
    }
    

提交回复
热议问题