Merge branch 'main' into CEC-3796

This commit is contained in:
Paul Adamsen
2023-10-24 09:27:58 -04:00
committed by GitHub
18 changed files with 373 additions and 30 deletions

View File

@@ -0,0 +1,16 @@
export default function unionIntersect(...arrays) {
if (arrays.length === 0) return [];
if (arrays.length === 1) return arrays[0];
const result = [];
const sets = arrays.slice(1).map(array => new Set(array));
// TODO: Use a priority queue
arrays[0].forEach((value) => {
if (sets.every(set => set.has(value))) {
result.push(value);
}
});
return result;
}

View File

@@ -0,0 +1,93 @@
import unionIntersect from "./unionIntersect";
const tests = [
[
"merges identical arrays",
[
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
],
[1, 2, 3, 4, 5],
],
[
"merges arrays with smaller initial array",
[
[1, 2, 4, 5],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
],
[1, 2, 4, 5],
],
[
"merges arrays with larger initial array",
[
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
],
[1, 2, 3, 4, 5],
],
[
"merges arrays with empty initial array",
[
[],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
],
[],
],
[
"merges arrays with empty array",
[
[1, 2, 3, 4, 5],
[],
[1, 2, 3, 4, 5],
],
[],
],
[
"merges arrays with empty array",
[
[1, 2, 3, 4, 5],
[],
[1, 2, 3, 4, 5],
],
[],
],
[
"merges arrays with no overlap",
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
],
[],
],
[
"merges arrays with some overlap",
[
[1, 2, 3, 4, 5, 6],
[4, 5, 6, 7, 8, 9],
[6, 7, 8, 9, 10, 11, 12],
],
[6],
],
[
"does not support objects",
[
[{ key: "value" }, { key: "value2" }],
[{ key: "value" }, { key: "value3" }],
[{ key: "value" }, { key: "value4" }],
],
[],
],
];
describe("unionIntersect", () => {
tests.forEach(([desc, arrays, expected]) => {
it(desc, () => {
expect(unionIntersect(...arrays)).toStrictEqual(expected);
});
});
});