👔Set extension

JSvalueobjectbuilt-inSet ⟩ extension

const { range } = require('./Iterable.js');      // iterable methods (.every())

// 2022.12.30 - 16:26 - first version + minor fix
//
// --------------------------------------------------------------------
// ⭐ Set extension            ❗: mutating method
// --------------------------------------------------------------------
// 🔹 .copy()                - shallow copy (object references copied)
// 🔹 .isSubsetOf()          - check if is another set's subset
// 🔹 .isEqualTo()           - check if two sets have the same elements
// --------------------------------------------------------------------
Object.defineProperties(Set.prototype, {

    // 🔹 .copy()
    copy: {
        value: function() {
            return new Set(this);    // shallow copy
        },
    },

    // 🔹 .isSubsetOf()
    isSubsetOf: {
        value: function(set2) {
            if (this.size > set2.size) return false;
            return this.every(elem => set2.has(elem));
        },
    },

    // 🔹 .isEqualTo()
    isEqualTo: {
        value: function(set2) {
            if (this.size !== set2.size) return false;
            // same size, subset => equal
            return this.isSubsetOf(set2);    
        },
    },
    
});

// export
module.exports = {};

Last updated