Last active
May 15, 2021 21:14
-
-
Save sebinsua/f0ccc00b1e2fa510c827d91d59425baf to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| #!/usr/bin/env node | |
| function intersect(x, y) { | |
| const setX = new Set(x); | |
| const setY = new Set(y); | |
| let intersected = []; | |
| for (let value of setX) { | |
| // I worked with Sets because of an assumption that this is | |
| // cheaper than Array#includes. | |
| if (setY.has(value)) { | |
| intersected.push(value); | |
| } | |
| } | |
| return intersected; | |
| } | |
| function union(x, y) { | |
| return Array.from(new Set([...x, ...y])); | |
| } | |
| function difference(x, y) { | |
| const setX = new Set(x); | |
| const setY = new Set(y); | |
| let complements = []; | |
| for (let value of setY) { | |
| if (!setX.has(value)) { | |
| complements.push(value); | |
| } | |
| } | |
| return complements; | |
| } | |
| // Apparently also known as a disjunctive union. | |
| function symmetricDifference(a, b) { | |
| const c = union(a, b); | |
| // Probably there's a more efficent way of doing this | |
| // but this is at least expressive. | |
| return difference(intersect(a, b), c); | |
| } | |
| console.log(intersect([1, 2, 3, 4, 11], [3, 4, 5, 6, 7, 8, 9])); | |
| console.log(union([1, 2, 3, 4, 11], [3, 4, 5, 6, 7, 8, 9])); | |
| console.log(difference([1, 2, 3, 4, 11], [3, 4, 5, 6, 7, 8, 9])); | |
| console.log(symmetricDifference([1, 2, 3, 102], [2, 3, 4, 5, 99, 100])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
But what about when we want to get out all items with the same identity but a changed inner property?