๐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