How do the ES6 Map shims work

后端 未结 3 1334
不知归路
不知归路 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:53

    There are two ways that come to mind. First, obviously, you can have an array of keys, and search it linearly:

    Map1 = {
        keys: [],
        values: [],
    };
    
    Map1.set = function(key, val) {
        var k = this.keys.indexOf(key);
        if(k < 0)
            this.keys[k = this.keys.length] = key;
        this.values[k] = val;
    };
    
    Map1.get = function(key) {
        return this.values[this.keys.indexOf(key)];
    };
    
    
    foo = {};
    bar = {};
    
    Map1.set(foo, 'xxx');
    Map1.set(bar, 'yyy');
    
    document.write(Map1.get(foo) + Map1.get(bar) + "
    ")

    The second option is to add a special "key" marker to an object which is used as a key:

    Map2 = {
        uid: 0,
        values: {}
    };
    
    Map2.set = function(key, val) {
        key = typeof key === 'object'
            ? (key.__uid = key.__uid || ++this.uid)
            : String(key);
        this.values[key] = val;
    };
    
    Map2.get = function(key) {
        key = typeof key === 'object'
            ? key.__uid
            : String(key);
        return this.values[key];
    };
    
    
    foo = {};
    bar = {};
    
    Map2.set(foo, 'xxx');
    Map2.set(bar, 'yyy');
    
    document.write(Map2.get(foo) + Map2.get(bar) + "
    ")

    Unlike the 1st option, the second one is O(1). It can be done more accurately by making uid non-writable/enumerable. Also, each Map should have its own "uid" name (this can be easily set up in the Map constructor).

提交回复
热议问题