Skip to content

feat: mix with regexp object #58

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Feb 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,15 +67,16 @@ TS Regex Builder allows you to build complex regular expressions using domain-sp

Terminology:
- regex construct (`RegexConstruct`) - common name for all regex constructs like character classes, quantifiers, and anchors.
- regex element (`RegexElement`) - a fundamental building block of a regular expression, defined as either a regex construct or a string.
- regex element (`RegexElement`) - a fundamental building block of a regular expression, defined as either a regex construct, a string, or `RegExp` literal (`/.../`).
- regex sequence (`RegexSequence`) - a sequence of regex elements forming a regular expression. For developer convenience, it also accepts a single element instead of an array.

Most of the regex constructs accept a regex sequence as their argument.

Examples of sequences:
- single element (construct): `capture('abc')`
- single element (construct): `capture('Hello')`
- single element (string): `'Hello'`
- array of elements: `['USD', oneOrMore(digit)]`
- single element (`RegExp` literal): `/Hello/`
- array of elements: `['USD', oneOrMore(digit), /Hello/]`

Regex constructs can be composed into a tree structure:

Expand Down
2 changes: 1 addition & 1 deletion docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ The sequence of regex elements forming a regular expression. For developer conve

### `RegexElement`

Fundamental building blocks of a regular expression, defined as either a regex construct or a string.
Fundamental building blocks of a regular expression, defined as either a regex construct, a string, or a `RegExp` literal (`/.../`).

### `RegexConstruct`

Expand Down
22 changes: 22 additions & 0 deletions src/encoder/__tests__/encoder.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { buildPattern, buildRegExp } from '../../builders';
import { capture } from '../../constructs/capture';
import { choiceOf } from '../../constructs/choice-of';
import { oneOrMore, optional, zeroOrMore } from '../../constructs/quantifiers';
import { repeat } from '../../constructs/repeat';

Expand Down Expand Up @@ -43,6 +45,26 @@ test('`buildPattern` escapes special characters', () => {
expect([oneOrMore('.*'), zeroOrMore('[]{}')]).toEqualRegex(/(?:\.\*)+(?:\[\]\{\})*/);
});

test('`buildRegExp` accepts RegExp object', () => {
expect(buildRegExp(/abc/)).toEqual(/abc/);
expect(buildRegExp(oneOrMore(/abc/))).toEqual(/(?:abc)+/);
expect(buildRegExp(repeat(/abc/, 5))).toEqual(/(?:abc){5}/);
expect(buildRegExp(capture(/abc/))).toEqual(/(abc)/);
expect(buildRegExp(choiceOf(/a/, /b/))).toEqual(/a|b/);
expect(buildRegExp(choiceOf(/a|b/, /c/))).toEqual(/a|b|c/);
});

test('`buildRegExp` detects common atomic patterns', () => {
expect(buildRegExp(/a/)).toEqual(/a/);
expect(buildRegExp(/[a-z]/)).toEqual(/[a-z]/);
expect(buildRegExp(/(abc)/)).toEqual(/(abc)/);
expect(buildRegExp(oneOrMore(/a/))).toEqual(/a+/);
expect(buildRegExp(oneOrMore(/[a-z]/))).toEqual(/[a-z]+/);
expect(buildRegExp(oneOrMore(/(abc)/))).toEqual(/(abc)+/);
expect(buildRegExp(repeat(/a/, 5))).toEqual(/a{5}/);
expect(buildRegExp(oneOrMore(/(a|b|c)/))).toEqual(/(a|b|c)+/);
});

test('`buildRegExp` throws error on unknown element', () => {
expect(() =>
// @ts-expect-error intentionally passing incorrect object
Expand Down
35 changes: 35 additions & 0 deletions src/encoder/encoder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ function encodeNode(element: RegexElement): EncodeResult {
return encodeText(element);
}

if (typeof element === 'object' && element instanceof RegExp) {
return encodeRegExp(element);
}

if (typeof element.encode !== 'function') {
throw new Error(`\`encodeNode\`: unknown element type ${element.type}`);
}
Expand All @@ -42,6 +46,37 @@ function encodeText(text: string): EncodeResult {
};
}

function encodeRegExp(regexp: RegExp): EncodeResult {
const pattern = regexp.source;

if (pattern.length === 0) {
throw new Error('`encodeRegExp`: received regexp should not be empty');
}

// Encode at safe precedence
return {
precedence: isAtomicPattern(regexp.source) ? 'atom' : 'disjunction',
pattern,
};
}

// This is intended to catch only some popular atomic patterns like char classes.
function isAtomicPattern(pattern: string): boolean {
if (pattern.length === 1) {
return true;
}

if (pattern.startsWith('[') && pattern.endsWith(']') && pattern.match(/[[\]]/g)?.length === 2) {
return true;
}

if (pattern.startsWith('(') && pattern.endsWith(')') && pattern.match(/[()]/g)?.length === 2) {
return true;
}

return false;
}

function concatSequence(encoded: EncodeResult[]): EncodeResult {
if (encoded.length === 1) {
return encoded[0]!;
Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export type RegexSequence = RegexElement[] | RegexElement;
/**
* Fundamental building block of a regular expression, defined as either a regex construct or a string.
*/
export type RegexElement = RegexConstruct | string;
export type RegexElement = RegexConstruct | string | RegExp;

/**
* Common interface for all regex constructs like character classes, quantifiers, and anchors.
Expand Down