class MathSet extends Set{
constructor(arr){
super(arr);
}
union(set){
return new MathSet([...this, ...set])
}
intersection(set){
return new MathSet([...this].filter(x => set.has(x)));
}
difference(set){
return new MathSet([...this].filter(x => !set.has(x)));
}
cartesian(set){
return new MathSet( [...this].reduce((acc, i)=> [...acc, [...set].map(j=>[i,j])], []) )
}
}
let x = new MathSet([1,2,3]);
let y = new MathSet([1,2,3,4,5]);
console.log(JSON.stringify([...x.cartesian(y)]));
//[
// [[1,1],[1,2],[1,3],[1,4],[1,5]],
// [[2,1],[2,2],[2,3],[2,4],[2,5]],
// [[3,1],[3,2],[3,3],[3,4],[3,5]]
// ]
cartesian
[[1,1],[1,2],[1,3],[1,4],[1,5],[2,1],[2,2],[2,3],[2,4],[2,5],[3,1],[3,2],[3,3],[3,4],[3,5]]
To flatten the arrays you need just one more spread:
return new MathSet( [...this].reduce((acc, i)=> [...acc, ...[...set].map(j=>[i,j])], []) )
// ^^^
(or acc.concat(Array.from(set, j=>[i,j]))
)