So, whilst Set
s were a great addition to JavaScript, there did seem to be some glaring omissions. The most obvious of these were the basic set operations: union
, intersection
, and difference
.
We can easily add these with Metho:
import * as metho from "metho"
const target = Set.prototype
export const union = Metho.add(
target,
function(set) {
return new Set([...this, ...set])
}
)
export const intersect = Metho.add(
target,
function(set) {
return new Set([...this].filter(i=>set.has(i)))
}
)
export const difference = Metho.add(
target,
function(set) {
return new Set([...this].filter(i=>!set.has(i)))
}
)
const a = new Set([1, 2, 3])
const b = new Set([3, 4, 5])
// everything from both sets
console.log( a[union(b)] ) // Set(5)[ 1, 2, 3, 4, 5 ]
// everything that exists in both set a and set b
console.log( a[intersect(b)] ) // Set [ 3 ]
// everything that exists in set a, but not in set b
console.log( a[difference(b)] ) // Set [ 1, 2 ]
I have made these extensions available in the metho-set
library
Top comments (0)