Skip to content

Commit 7ac0396

Browse files
committed
chore: refactor
1 parent e0fd84e commit 7ac0396

File tree

3 files changed

+20
-19
lines changed

3 files changed

+20
-19
lines changed

src/characterClasses.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { Any, Digit, Whitespace, Word } from './types';
2-
import type { CompilerMap } from './types-internal';
2+
import type { CharacterClassCompilerMap } from './types-internal';
33

44
export const whitespace: Whitespace = { type: 'whitespace' };
55

@@ -14,4 +14,4 @@ export const compilers = {
1414
digit: '\\d',
1515
word: '\\w',
1616
any: '.',
17-
} satisfies CompilerMap;
17+
} satisfies CharacterClassCompilerMap;

src/compiler.ts

+14-14
Original file line numberDiff line numberDiff line change
@@ -34,26 +34,26 @@ function compileSingle(elements: RegexElement): string {
3434
return elements;
3535
}
3636

37-
if ('children' in elements) {
38-
const compiledChildren = compileList(elements.children);
37+
if (!('children' in elements)) {
38+
const characterCompiler = characterClasses[elements.type];
3939

40-
if (elements.type === 'repeat') {
41-
return compileRepeat(elements.config, compiledChildren);
40+
if (!characterCompiler) {
41+
throw new Error(`Unknown character type ${elements.type}`);
4242
}
4343

44-
const elementCompiler = quantifiers[elements.type];
45-
if (!elementCompiler) {
46-
throw new Error(`Unknown elements type ${elements.type}`);
47-
}
48-
49-
return elementCompiler(compiledChildren);
44+
return characterCompiler;
5045
}
5146

52-
const characterCompiler = characterClasses[elements.type];
47+
const compiledChildren = compileList(elements.children);
48+
49+
if (elements.type === 'repeat') {
50+
return compileRepeat(elements.config, compiledChildren);
51+
}
5352

54-
if (!characterCompiler) {
55-
throw new Error(`Unknown character type ${elements.type}`);
53+
const elementCompiler = quantifiers[elements.type];
54+
if (!elementCompiler) {
55+
throw new Error(`Unknown elements type ${elements.type}`);
5656
}
5757

58-
return characterCompiler;
58+
return elementCompiler(compiledChildren);
5959
}

src/types-internal.ts

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Compilation
22
export type ElementCompiler = (compiledChildren: string) => string;
3-
export type CompilerMap =
4-
| Record<string, ElementCompiler>
5-
| Record<string, string>;
3+
4+
export type CompilerMap = Record<string, ElementCompiler>;
5+
6+
export type CharacterClassCompilerMap = Record<string, string>;

0 commit comments

Comments
 (0)