Skip to content

Instantly share code, notes, and snippets.

@ernestlv
Last active June 6, 2023 15:54
Show Gist options
  • Save ernestlv/0b63c15e6df8472ec64b36fe241ebfe3 to your computer and use it in GitHub Desktop.
Save ernestlv/0b63c15e6df8472ec64b36fe241ebfe3 to your computer and use it in GitHub Desktop.
Calculate the union of two sets. It merges common elements using expression: { ...mapA[b.key], ...b }
/* it is either in A or B */
function union(arrA, arrB) {
const mapA = arrA.reduce((res, a) => ({ ...res, [a.key]:a }), {});
const inter = arrB.reduce((res, b) => (b.key in mapA) ? [ ...res, { ...mapA[b.key], ...b } ] : res, []);
const mapInter = inter.reduce((res, i) => ({ ...res, [i.key]:i }), {});
const diffA = arrA.reduce((res, a) => !(a.key in mapInter) ? [ ...res, a ] : res, []);
const diffB = arrB.reduce((res, b) => !(b.key in mapInter) ? [ ...res, b ] : res, []);
return [ ...diffA, ...inter, ...diffB ];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment