ECMAScript 6: what is WeakSet for?

后端 未结 7 718
北荒
北荒 2020-11-29 22:20

The WeakSet is supposed to store elements by weak reference. That is, if an object is not referenced by anything else, it should be cleaned from the WeakSet.

I have

7条回答
  •  旧时难觅i
    2020-11-29 22:33

    WeakSet is a simplification of WeakMap for where your value is always going to be boolean true. It allows you to tag JavaScript objects so to only do something with them once or to maintain their state in respect to a certain process. In theory as it doesn't need to hold a value it should use a little less memory and perform slightly faster than WeakMap.

    var [touch, untouch] = (() => {
        var seen = new WeakSet();
        return [
            value => seen.has(value)) || (seen.add(value), !1),
            value => !seen.has(value) || (seen.delete(value), !1)
        ];
    })();
    
    function convert(object) {
        if(touch(object)) return;
        extend(object, yunoprototype); // Made up.
    };
    
    function unconvert(object) {
        if(untouch(object)) return;
        del_props(object, Object.keys(yunoprototype)); // Never do this IRL.
    };
    

提交回复
热议问题