sabithpocker sabithpocker - 2 months ago 5
Javascript Question

Cartesian product using reduce, map and spread is grouping the result which need to be flattened

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]]
// ]


With
cartesian
function expected result is a flattened version of the above array (
[[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]]
), but as you can see somehow its getting grouped into three arrays. The reduce is keeping on concatenating earlier result with spreaded version of new results. Any guess on what I am doing wrong?

Answer

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])))

Comments