👔Set extension
JS ⟩ value ⟩ object⟩ built-in ⟩ Set ⟩ extension
replit ⟩ 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 = {};
// ⭐ 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));
array.every(), Array.from()
Last updated