1
0
mirror of https://github.com/lensapp/lens.git synced 2025-05-20 05:10:56 +00:00

chore: Introduce utility function for "pattern matching" using regex

Co-authored-by: Janne Savolainen <janne.savolainen@live.fi>
Signed-off-by: Iku-turso <mikko.aspiala@gmail.com>
This commit is contained in:
Iku-turso 2023-05-09 13:05:03 +03:00 committed by Janne Savolainen
parent ce31715cfd
commit 7ca54d8f07
2 changed files with 59 additions and 0 deletions

View File

@ -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();
});
});

View File

@ -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;
};