perf(editor): improve array intersection utility function (#4503)

This commit is contained in:
Csaba Tuncsik 2022-11-02 15:03:55 +01:00 committed by GitHub
parent 3c9ad02ce3
commit b0df810745
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 46 additions and 1 deletions

View file

@ -0,0 +1,41 @@
import { isEmpty, intersection } from "@/utils";
describe("Utils", () => {
describe("isEmpty", () => {
it.each([
[undefined, true],
[null, true],
[{}, true],
[{ a: {}}, true],
[{ a: { b: []}}, true],
[{ a: { b: [1]}}, false],
[[], true],
[[{}, {}, {}], true],
[[{}, null, false], true],
[[{}, null, false, 1], false],
[[[], [], []], true],
["", true],
["0", false],
[0, false],
[1, false],
[false, true],
[true, false],
])(`for value %s should return %s`, (value, expected) => {
expect(isEmpty(value)).toBe(expected);
});
});
describe("intersection", () => {
it("should return the intersection of two arrays", () => {
expect(intersection([1, 2, 3], [2, 3, 4])).toEqual([2, 3]);
});
it("should return the intersection of two arrays without duplicates", () => {
expect(intersection([1, 2, 2, 3], [2, 2, 3, 4])).toEqual([2, 3]);
});
it("should return the intersection of four arrays without duplicates", () => {
expect(intersection([1, 2, 2, 3, 4], [2, 3, 3, 4], [2, 1, 5, 4, 4, 1], [2, 4, 5, 5, 6, 7])).toEqual([2, 4]);
});
});
});

View file

@ -57,4 +57,8 @@ export const isEmpty = (value?: unknown): boolean => {
return false;
};
export const intersection = <T>(a: T[], b:T[]): T[] => a.filter(Set.prototype.has, new Set(b));
export const intersection = <T>(...arrays: T[][]): T[] => {
const [a, b, ...rest] = arrays;
const ab = a.filter(v => b.includes(v));
return [...new Set(rest.length ? intersection(ab, ...rest) : ab)];
};