From f7abe3d156f8039c497c5bdf28e0b7ccf2f94d25 Mon Sep 17 00:00:00 2001 From: Csaba Tuncsik Date: Tue, 1 Nov 2022 23:01:14 +0100 Subject: [PATCH] perf(editor): improve array intersection utility function --- packages/editor-ui/src/utils.test.ts | 41 ++++++++++++++++++++++++++++ packages/editor-ui/src/utils.ts | 6 +++- 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 packages/editor-ui/src/utils.test.ts diff --git a/packages/editor-ui/src/utils.test.ts b/packages/editor-ui/src/utils.test.ts new file mode 100644 index 0000000000000..1d2aada70aa4c --- /dev/null +++ b/packages/editor-ui/src/utils.test.ts @@ -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]); + }); + }); +}); diff --git a/packages/editor-ui/src/utils.ts b/packages/editor-ui/src/utils.ts index 7880c79de9a09..15a34e8cea37e 100644 --- a/packages/editor-ui/src/utils.ts +++ b/packages/editor-ui/src/utils.ts @@ -57,4 +57,8 @@ export const isEmpty = (value?: unknown): boolean => { return false; }; -export const intersection = (a: T[], b:T[]): T[] => a.filter(Set.prototype.has, new Set(b)); +export const intersection = (...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)]; +};