From 7ca54d8f078a2a1816c13424c7e7c2b91c806503 Mon Sep 17 00:00:00 2001 From: Iku-turso Date: Tue, 9 May 2023 13:05:03 +0300 Subject: [PATCH] chore: Introduce utility function for "pattern matching" using regex Co-authored-by: Janne Savolainen Signed-off-by: Iku-turso --- .../src/common/k8s-api/get-match-for.test.ts | 42 +++++++++++++++++++ .../core/src/common/k8s-api/get-match-for.ts | 17 ++++++++ 2 files changed, 59 insertions(+) create mode 100644 packages/core/src/common/k8s-api/get-match-for.test.ts create mode 100644 packages/core/src/common/k8s-api/get-match-for.ts diff --git a/packages/core/src/common/k8s-api/get-match-for.test.ts b/packages/core/src/common/k8s-api/get-match-for.test.ts new file mode 100644 index 0000000000..255c39bb78 --- /dev/null +++ b/packages/core/src/common/k8s-api/get-match-for.test.ts @@ -0,0 +1,42 @@ +/** + * Copyright (c) OpenLens Authors. All rights reserved. + * Licensed under MIT License. See LICENSE in root directory for more information. + */ +import { getMatchFor } from "./get-match-for"; + +describe("get-match-for", () => { + it("given non-matching and matching regex, when called with a string, returns match", () => { + const getMatch = getMatchFor(/some-match/, /some-non-match/); + + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const match = [...getMatch("some-match")!]; + + expect(match).toEqual(["some-match"]); + }); + + it("given multiple matching regex, when called with a string, returns first match", () => { + const getMatch = getMatchFor(/match/, /some-match/); + + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const match = [...getMatch("match")!]; + + expect(match).toEqual(["match"]); + }); + + it("given multiple matching regex, when called with a string, returns first match", () => { + const getMatch = getMatchFor(/non-match/, /some-match/, /match/); + + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const [...match] = getMatch("some-match")!; + + expect(match).toEqual(["some-match"]); + }); + + it("given no matching regex, when called with a string, returns undefined", () => { + const getMatch = getMatchFor(/match/, /some-match/); + + const match = getMatch("some-other-string"); + + expect(match).toBeUndefined(); + }); +}); diff --git a/packages/core/src/common/k8s-api/get-match-for.ts b/packages/core/src/common/k8s-api/get-match-for.ts new file mode 100644 index 0000000000..3c3dd1c68a --- /dev/null +++ b/packages/core/src/common/k8s-api/get-match-for.ts @@ -0,0 +1,17 @@ +/** + * Copyright (c) OpenLens Authors. All rights reserved. + * Licensed under MIT License. See LICENSE in root directory for more information. + */ +export const getMatchFor = + (...patterns: RegExp[]) => + (reference: string) => { + for (const pattern of patterns) { + const match = reference.match(pattern); + + if (match) { + return match; + } + } + + return undefined; + };