Skip to content

Commit

Permalink
util: trimPrefix and trimSuffix methods
Browse files Browse the repository at this point in the history
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
  • Loading branch information
crazy-max committed Jul 6, 2023
1 parent ddcd63c commit 70c0e12
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
35 changes: 35 additions & 0 deletions __tests__/util.test.ts
Expand Up @@ -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()}`;
Expand Down
22 changes: 22 additions & 0 deletions src/util.ts
Expand Up @@ -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);
}
}

0 comments on commit 70c0e12

Please sign in to comment.