What's a good mathematical sets implementation in JavaScript?

前端 未结 7 1409
予麋鹿
予麋鹿 2021-02-06 16:19

Where is a good mathematical sets implementation for JavaScript? It should include efficient implementations of intersection, union, complement, and (for bonus points) the Carte

7条回答
  •  悲哀的现实
    2021-02-06 16:51

    I don't know of any existing implementations, but if your set elements are strings (or have a unique string representation) you can use JavaScript objects pretty easily. The elements would be the object properties, and the value could be anything.

    // Make a set from an array of elements
    function makeSet(items) {
        var set = {};
        for (var i = 0; i < items.length; i++) {
            set[items[i]] = true;
        }
        return set;
    }
    
    function copyInto(s, copy) {
        for (var item in s) {
            if (s[item] === true) {
                copy[item] = true;
            }
        }
    }
    
    function union(s1, s2) {
        var u = {};
        copyInto(s1, u);
        copyInto(s2, u);
        return u;
    }
    
    function intersection(s1, s2) {
        var i = {};
        for (var item in s1) {
            if (s1[item] === true && s2[item] === true) {
                i[item] = true;
            }
        }
        return i;
    }
    
    function difference(s1, s2) {
        var diff = {};
        copyInto(s1, diff);
        for (var item in s2) {
            if (s2[item] === true) {
                delete diff[item];
            }
        }
        return diff;
    }
    
    // etc.
    

    You could also use item in set or set.hasOwnProperty(item) instead of set[item] === true, but checking by for true explicitly, you automatically ignore any functions that might be attached to the object (in case someone modified Object.prototype, or it's not a plain object).

提交回复
热议问题