From 70c0e12f74c50e2b207702f9ecf09eb2c7d75305 Mon Sep 17 00:00:00 2001 From: CrazyMax Date: Thu, 6 Jul 2023 13:24:04 +0200 Subject: [PATCH] util: trimPrefix and trimSuffix methods Signed-off-by: CrazyMax --- __tests__/util.test.ts | 35 +++++++++++++++++++++++++++++++++++ src/util.ts | 22 ++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/__tests__/util.test.ts b/__tests__/util.test.ts index 7f41d0d..2dfbc30 100644 --- a/__tests__/util.test.ts +++ b/__tests__/util.test.ts @@ -232,6 +232,41 @@ describe('isValidRef', () => { }); }); +describe('trimPrefix', () => { + test.each([ + ['', 'abc', ''], + ['abc', 'a', 'bc'], + ['abc', 'ab', 'c'], + ['abc', '', 'abc'], + ['abc', '', 'abc'], + ['abc', 'd', 'abc'], + ['abc', 'abc', ''], + ['abc', 'abcd', 'abc'], + ['abcdabc', 'abc', 'dabc'], + ['abcabc', 'abc', 'abc'], + ['abcdabc', 'd', 'abcdabc'] + ])('given %p', async (str, prefix, expected) => { + expect(Util.trimPrefix(str, prefix)).toEqual(expected); + }); +}); + +describe('trimSuffix', () => { + test.each([ + ['', 'abc', ''], + ['abc', 'c', 'ab'], + ['abc', '', 'abc'], + ['abc', 'bc', 'a'], + ['abc', 'abc', ''], + ['abc', 'abcd', 'abc'], + ['abc', 'aabc', 'abc'], + ['abcdabc', 'abc', 'abcd'], + ['abcabc', 'abc', 'abc'], + ['abcdabc', 'd', 'abcdabc'] + ])('given %p', async (str, suffix, expected) => { + expect(Util.trimSuffix(str, suffix)).toEqual(expected); + }); +}); + // See: https://github.com/actions/toolkit/blob/a1b068ec31a042ff1e10a522d8fdf0b8869d53ca/packages/core/src/core.ts#L89 function getInputName(name: string): string { return `INPUT_${name.replace(/ /g, '_').toUpperCase()}`; diff --git a/src/util.ts b/src/util.ts index d281715..84373b3 100644 --- a/src/util.ts +++ b/src/util.ts @@ -111,4 +111,26 @@ export class Util { } return false; } + + public static trimPrefix(str: string, suffix: string): string { + if (!str || !suffix) { + return str; + } + const index = str.indexOf(suffix); + if (index !== 0) { + return str; + } + return str.substring(suffix.length); + } + + public static trimSuffix(str: string, suffix: string): string { + if (!str || !suffix) { + return str; + } + const index = str.lastIndexOf(suffix); + if (index === -1 || index + suffix.length !== str.length) { + return str; + } + return str.substring(0, index); + } }