How to customize object equality for JavaScript Set

后端 未结 9 1366
臣服心动
臣服心动 2020-11-22 16:48

New ES 6 (Harmony) introduces new Set object. Identity algorithm used by Set is similar to === operator and so not much suitable for comparing objects:

9条回答
  •  不知归路
    2020-11-22 16:52

    As mentioned in jfriend00's answer customization of equality relation is probably not possible.

    Following code presents an outline of computationally efficient (but memory expensive) workaround:

    class GeneralSet {
    
        constructor() {
            this.map = new Map();
            this[Symbol.iterator] = this.values;
        }
    
        add(item) {
            this.map.set(item.toIdString(), item);
        }
    
        values() {
            return this.map.values();
        }
    
        delete(item) {
            return this.map.delete(item.toIdString());
        }
    
        // ...
    }
    

    Each inserted element has to implement toIdString() method that returns string. Two objects are considered equal if and only if their toIdString methods returns same value.

提交回复
热议问题