Skip to content

Commit

Permalink
feat(utils): 新增 nextUniqueName
Browse files Browse the repository at this point in the history
  • Loading branch information
cloudcome committed Apr 15, 2023
1 parent 9f65bbf commit f62c3ec
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
9 changes: 9 additions & 0 deletions src/utils/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,12 @@ export function toTypePath(props: string[]): string {
export function joinSlices(slices: Array<string | undefined>, separator = '\n') {
return slices.filter(Boolean).join(separator);
}

export function nextUniqueName(refName: string, nameCountMap: Map<string, number>) {
// abc123 -> abc
const baseName = refName.replace(/\d+$/, '');
const count = nameCountMap.get(baseName) || 0;
const nextCount = count + 1;
nameCountMap.set(baseName, nextCount);
return nextCount === 1 ? baseName : baseName + nextCount;
}
19 changes: 18 additions & 1 deletion test/utils/string.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
import { buildName, findOrigin, joinSlices, RefInfo, refToType, toTypePath, varString } from '../../src/utils/string';
import {
buildName,
findOrigin,
joinSlices,
nextUniqueName,
RefInfo,
refToType,
toTypePath,
varString,
} from '../../src/utils/string';

test('buildName', () => {
expect(buildName('!')).toEqual('unnamed');
Expand Down Expand Up @@ -60,3 +69,11 @@ test('joinSlices', () => {
expect(joinSlices(['', undefined, ''])).toEqual('');
expect(joinSlices(['1', undefined, '2', ''])).toEqual('1\n2');
});

test('nextUniqueName', () => {
const map = new Map<string, number>();
expect(nextUniqueName('abc', map)).toBe('abc');
expect(nextUniqueName('abc', map)).toBe('abc2');
expect(nextUniqueName('abc', map)).toBe('abc3');
expect(nextUniqueName('abc2', map)).toBe('abc4');
});

0 comments on commit f62c3ec

Please sign in to comment.