> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/js/val/builtin/set/set-extension.md).

# Set extension

[JS](/web/js.md) ⟩ [value](/web/js/val.md) ⟩ [object](/web/js/val/obj.md)⟩ [built-in](/web/js/val/builtin.md) ⟩ [Set](/web/js/val/builtin/set.md) ⟩ extension&#x20;

{% tabs %}
{% tab title="💾 程式" %}

* replit ⟩ [Set extension](https://replit.com/@pegasusroe/Set-extension#ext/Set_ext.js)

```javascript
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 = {};
```

{% endtab %}

{% tab title="💈範例" %}

```javascript
// ⭐ import
const _Set = require('./ext/Set_ext.js');      // Set extension

const s1 = new Set([1,2,3]);
const s2 = s1.copy();
const s3 = s1.copy().add(4);

// ✅ log expressions that never throw
// ---------------------------------------------------------------------------
;[
    s2.has(1),            // true
    s2,                   // {1,2,3}
    s3,                   // {1,2,3,4}
    s1 === s2,            // false
    
    s1.isSubsetOf(s2),    // true
    s2.isSubsetOf(s1),    // true
    s1.isEqualTo(s2),     // true

    s3.isSubsetOf(s1),    // false
    s1.isSubsetOf(s3),    // true
    s1.isEqualTo(s3),     // false

].forEach(x => log(x));
```

{% endtab %}

{% tab title="📘 手冊" %}

* [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#instance_methods)
* array.[every](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every)(), [Array.from](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/from)()
  {% endtab %}
  {% endtabs %}
