๐Ÿ‘”Set extension

JS โŸฉ value โŸฉ objectโŸฉ built-in โŸฉ Set โŸฉ 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