segment-matcher
Version:
Segment Matcher - TypeScript version with dual ESM/CJS format support
138 lines (137 loc) • 3.38 kB
JavaScript
/**
* Number类型匹配器
*
* 支持整数和小数:123, 123.45, 0, 0.5, -10, -3.14
*/
export class NumberTypeMatcher {
constructor() {
this.regex = /^-?\d+(\.\d+)?$/;
}
match(text) {
if (!this.regex.test(text)) {
return { success: false };
}
const value = Number(text);
if (isNaN(value)) {
return { success: false };
}
return { success: true, value };
}
}
/**
* Integer类型匹配器
*
* 只支持整数:123, 0, -5
*/
export class IntegerTypeMatcher {
constructor() {
this.regex = /^-?\d+$/;
}
match(text) {
if (!this.regex.test(text)) {
return { success: false };
}
const value = parseInt(text, 10);
if (isNaN(value)) {
return { success: false };
}
return { success: true, value };
}
}
/**
* Float类型匹配器
*
* 只支持浮点数(必须包含小数点):123.45, 0.5, -3.14
*/
export class FloatTypeMatcher {
constructor() {
this.regex = /^-?\d+\.\d+$/;
}
match(text) {
if (!this.regex.test(text)) {
return { success: false };
}
const value = parseFloat(text);
if (isNaN(value)) {
return { success: false };
}
return { success: true, value };
}
}
/**
* Boolean类型匹配器
*
* 支持true/false字符串:true, false
*/
export class BooleanTypeMatcher {
constructor() {
this.regex = /^(true|false)$/;
}
match(text) {
if (!this.regex.test(text)) {
return { success: false };
}
const value = text === 'true';
return { success: true, value };
}
}
/**
* Text类型匹配器
*
* 直接返回文本内容,总是成功匹配
*/
export class TextTypeMatcher {
match(text) {
return { success: true, value: text };
}
}
/**
* 类型匹配器注册表
*
* 管理所有可用的类型匹配器,提供统一的访问接口。
*/
export class TypeMatcherRegistry {
/**
* 获取指定类型的匹配器
*
* @param dataType - 数据类型名称
* @returns 对应的类型匹配器,如果不存在则返回null
*/
static getMatcher(dataType) {
return this.matchers.get(dataType) || null;
}
/**
* 检查是否支持指定类型的特殊匹配
*
* @param dataType - 数据类型名称
* @returns 是否支持特殊匹配
*/
static hasSpecialMatcher(dataType) {
// text类型不需要特殊处理,其他类型都需要
return this.matchers.has(dataType) && dataType !== 'text';
}
/**
* 注册新的类型匹配器
*
* @param dataType - 数据类型名称
* @param matcher - 类型匹配器实例
*/
static registerMatcher(dataType, matcher) {
this.matchers.set(dataType, matcher);
}
/**
* 获取所有支持的数据类型
*
* @returns 支持的数据类型列表
*/
static getSupportedTypes() {
return Array.from(this.matchers.keys());
}
}
TypeMatcherRegistry.matchers = new Map([
['number', new NumberTypeMatcher()],
['integer', new IntegerTypeMatcher()],
['float', new FloatTypeMatcher()],
['boolean', new BooleanTypeMatcher()],
['text', new TextTypeMatcher()],
]);