Last active
June 6, 2023 15:54
-
-
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 }
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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