Skip to content
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

refactor: cleanup char class #87

Merged
merged 3 commits into from
Apr 30, 2024
Merged
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
57 changes: 17 additions & 40 deletions src/constructs/character-class.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,6 @@
import type { EncodeResult } from '../encoder/types';
import type { RegexConstruct } from '../types';

export interface CharacterClass extends RegexConstruct {
type: 'characterClass';
escape?: string;
chars: string[];
ranges: CharacterRange[];
isNegated: boolean;
encode: () => EncodeResult;
}

/**
* Character range from start to end (inclusive).
*/
Expand All @@ -18,6 +9,14 @@ export interface CharacterRange {
end: string;
}

export interface CharacterClass extends RegexConstruct {
type: 'characterClass';
escape?: string;
chars?: string[];
ranges?: CharacterRange[];
isNegated?: boolean;
}

/**
* Matches any single character.
* Cannot be used as a part of character class.
Expand All @@ -30,54 +29,36 @@ export const any: EncodeResult = {
export const digit: CharacterClass = {
type: 'characterClass',
escape: '\\d',
chars: [],
ranges: [],
isNegated: false,
encode: encodeCharacterClass,
};

export const nonDigit: CharacterClass = {
type: 'characterClass',
escape: '\\D',
chars: [],
ranges: [],
isNegated: false,
encode: encodeCharacterClass,
};

export const word: CharacterClass = {
type: 'characterClass',
escape: '\\w',
chars: [],
ranges: [],
isNegated: false,
encode: encodeCharacterClass,
};

export const nonWord: CharacterClass = {
type: 'characterClass',
escape: '\\W',
chars: [],
ranges: [],
isNegated: false,
encode: encodeCharacterClass,
};

export const whitespace: CharacterClass = {
type: 'characterClass',
escape: '\\s',
chars: [],
ranges: [],
isNegated: false,
encode: encodeCharacterClass,
};

export const nonWhitespace: CharacterClass = {
type: 'characterClass',
escape: '\\S',
chars: [],
ranges: [],
isNegated: false,
encode: encodeCharacterClass,
};

Expand Down Expand Up @@ -107,9 +88,8 @@ export function charClass(...elements: CharacterClass[]): CharacterClass {

return {
type: 'characterClass',
chars: elements.map((c) => getAllChars(c)).flat(),
ranges: elements.map((c) => c.ranges).flat(),
isNegated: false,
chars: elements.map((c) => getAllChars(c) ?? []).flat(),
ranges: elements.map((c) => c.ranges ?? []).flat(),
encode: encodeCharacterClass,
};
}
Expand All @@ -129,9 +109,7 @@ export function charRange(start: string, end: string): CharacterClass {

return {
type: 'characterClass',
chars: [],
ranges: [{ start, end }],
isNegated: false,
encode: encodeCharacterClass,
};
}
Expand All @@ -146,15 +124,14 @@ export function anyOf(characters: string): CharacterClass {
return {
type: 'characterClass',
chars,
ranges: [],
isNegated: false,
encode: encodeCharacterClass,
};
}

export function negated(element: CharacterClass): CharacterClass {
return {
type: 'characterClass',
escape: element.escape,
chars: element.chars,
ranges: element.ranges,
isNegated: !element.isNegated,
Expand All @@ -168,27 +145,27 @@ export function negated(element: CharacterClass): CharacterClass {
export const inverted = negated;

function encodeCharacterClass(this: CharacterClass): EncodeResult {
if (this.escape === undefined && this.chars.length === 0 && this.ranges.length === 0) {
if (this.escape === undefined && !this.chars?.length && !this.ranges?.length) {
throw new Error('Character class should contain at least one character or character range');
}

// Direct rendering for single-character class
if (this.escape !== undefined && !this.chars.length && !this.ranges.length && !this.isNegated) {
// Direct rendering for escapes
if (this.escape !== undefined && !this.chars?.length && !this.ranges?.length && !this.isNegated) {
return {
precedence: 'atom',
pattern: this.escape,
};
}

const allChars = getAllChars(this);
const allChars = getAllChars(this) ?? [];

// If passed characters includes hyphen (`-`) it need to be moved to
// first (or last) place in order to treat it as hyphen character and not a range.
// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes#types
const hyphen = allChars.includes('-') ? '-' : '';
const caret = allChars.includes('^') ? '^' : '';
const otherChars = allChars.filter((c) => c !== '-' && c !== '^').join('');
const ranges = this.ranges.map(({ start, end }) => `${start}-${end}`).join('');
const ranges = this.ranges?.map(({ start, end }) => `${start}-${end}`).join('') ?? '';
const negation = this.isNegated ? '^' : '';

let pattern = `[${negation}${ranges}${otherChars}${caret}${hyphen}]`;
Expand All @@ -209,5 +186,5 @@ function getAllChars(characterClass: CharacterClass) {
return characterClass.chars;
}

return [characterClass.escape, ...characterClass.chars];
return [characterClass.escape, ...(characterClass.chars ?? [])];
}
Loading