Merge branch 'main' into CEC-3796
This commit is contained in:
16
src/utils/unionIntersect.js
Normal file
16
src/utils/unionIntersect.js
Normal 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;
|
||||
}
|
||||
93
src/utils/unionIntersect.test.js
Normal file
93
src/utils/unionIntersect.test.js
Normal 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);
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user