ts-regex-builder
Version:
Maintainable regular expressions for TypeScript and JavaScript.
58 lines • 1.56 kB
JavaScript
import { ensureText } from "../utils.mjs";
export function charClass(...elements) {
if (!elements.length) {
throw new Error('Expected at least one element');
}
return {
chars: elements.map(c => c.chars).flat(),
ranges: elements.map(c => c.ranges ?? []).flat(),
encode: encodeCharClass
};
}
export function charRange(start, end) {
if (start.length !== 1 || end.length !== 1) {
throw new Error(`Expected single characters, but received "${start}" & "${end}"`);
}
if (start > end) {
[start, end] = [end, start];
}
return {
chars: [],
ranges: [{
start,
end
}],
encode: encodeCharClass
};
}
export function anyOf(chars) {
ensureText(chars);
return {
chars: chars.split('').map(escapeChar),
encode: encodeCharClass
};
}
export function negated(element) {
return encodeCharClass.call(element, true);
}
export const inverted = negated;
function escapeChar(text) {
return text.replace(/[\]\\]/g, '\\$&');
}
function encodeCharClass(isNegated) {
const hyphen = this.chars.includes('-') ? '-' : '';
const caret = this.chars.includes('^') ? '^' : '';
const otherChars = this.chars.filter(c => c !== '-' && c !== '^').join('');
const ranges = this.ranges?.map(({
start,
end
}) => `${start}-${end}`).join('') ?? '';
const negation = isNegated ? '^' : '';
let pattern = `[${negation}${ranges}${otherChars}${caret}${hyphen}]`;
if (pattern === '[^-]') pattern = '[\\^-]';
return {
precedence: 'atom',
pattern
};
}
//# sourceMappingURL=char-class.mjs.map