Skip to content

Commit

Permalink
feat: 新增 findOrigin
Browse files Browse the repository at this point in the history
  • Loading branch information
cloudcome committed Apr 14, 2023
1 parent 9ecd29f commit a856c07
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 10 deletions.
19 changes: 16 additions & 3 deletions src/utils/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,28 @@ export function buildName(origin: string, bigger = false) {

export interface RefInfo {
type: string;
base: string;
props: string[];
}

export function refToTypeName(ref: string): RefInfo {
// #/components/schemas/{type}/{...prop}
export function refToType(ref: string): RefInfo {
const segs = ref.split('/').slice(3);
const type = segs.at(0)!;

return {
type: segs.at(0)!,
type,
base: `#/components/schemas/${type}`,
props: segs.slice(1),
};
}

export function findOrigin(source: string, relation: Map<string, string>) {
let origin = source;
let target: string | undefined;

while ((target = relation.get(origin))) {
origin = target;
}

return origin;
}
31 changes: 24 additions & 7 deletions test/utils/string.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { buildName, RefInfo, refToTypeName } from '../../src/utils/string';
import { buildName, findOrigin, RefInfo, refToType } from '../../src/utils/string';

test('buildName', () => {
expect(buildName('!')).toEqual('untitled');
expect(buildName('??')).toEqual('untitled');
expect(buildName('!')).toEqual('unnamed');
expect(buildName('??')).toEqual('unnamed');
expect(buildName('hello-world')).toEqual('helloWorld');
expect(buildName('hello-world123')).toEqual('helloWorld123');
expect(buildName('123hello-world123')).toEqual('helloWorld123');
Expand All @@ -11,17 +11,34 @@ test('buildName', () => {
expect(buildName('[[[123hello-world123]]]', true)).toEqual('HelloWorld123');
});

test('refToTypeName', () => {
expect(refToTypeName('#/components/schemas/T')).toEqual<RefInfo>({
test('refToType', () => {
expect(refToType('#/components/schemas/T')).toEqual<RefInfo>({
type: 'T',
base: '#/components/schemas/T',
props: [],
});
expect(refToTypeName('#/components/schemas/T/oo')).toEqual<RefInfo>({
expect(refToType('#/components/schemas/T/oo')).toEqual<RefInfo>({
type: 'T',
base: '#/components/schemas/T',
props: ['oo'],
});
expect(refToTypeName('#/components/schemas/T/oo/pp/qq')).toEqual<RefInfo>({
expect(refToType('#/components/schemas/T/oo/pp/qq')).toEqual<RefInfo>({
type: 'T',
base: '#/components/schemas/T',
props: ['oo', 'pp', 'qq'],
});
});

test('findOrigin', () => {
// a -> b -> c -> d
// x -> y
const relation = new Map([
['a', 'b'],
['b', 'c'],
['c', 'd'],
['x', 'y'],
]);
expect(findOrigin('a', relation)).toBe('d');
expect(findOrigin('x', relation)).toBe('y');
expect(findOrigin('y', relation)).toBe('y');
});

0 comments on commit a856c07

Please sign in to comment.