jsadvent/lib/Sets.js

48 lines
968 B
JavaScript
Raw Normal View History

2020-12-10 08:33:00 +00:00
module.exports = class Sets {
static and(set1, ...rest) {
const output = new Set();
for (const v of set1) {
if (rest.every((set) => set.has(v))) {
output.add(v);
}
}
return output;
}
static or(...sets) {
const output = new Set();
for (const set of sets) {
for (const v of set) {
output.add(v);
}
}
return output;
}
static xor(...sets) {
if (sets.length !== 2) {
throw new Error('xor is only meaningful on 2 sets');
}
const [l, r] = sets;
const output = new Set();
for (const v of l) {
if (!r.has(v)) {
output.add(v);
}
}
for (const v of r) {
if (!l.has(v)) {
output.add(v);
}
}
return output;
}
static counts(...sets) {
const output = new Map();
for (const set of sets) {
for (const v of set) {
output.set(v, (output.get(v) || 0n) + 1n);
}
}
return output;
}
};