Files
cut-abstractions/src/parsers.ts
2025-06-24 11:48:26 +08:00

51 lines
1.6 KiB
TypeScript

export type ParserCodeManager = Record<string,
{ name: string, exec: (...params: any[]) => string, type?: string, paramType?: 'array' | 'kv:number' }>;
export abstract class ParserBase {
protected codeManager: ParserCodeManager = {};
/**
* 代码调用转换命令
* @param codeKey
* @param params
* @returns
*/
exec(codeKey:string,params:unknown[]){
const code = this.codeManager[codeKey];
if (code) {
return code.exec(...params);
}
throw Error('未注册命令'+ codeKey);
}
/**
* 测试文本输入
* @param text
* @returns 返回结果
*/
execTest(text: string) {
let result: string = '';
for (const line of text.split('\n')) {
if(line.trim().length==0) continue;
const columns = line.split(' ');
const codeKey = columns[0].toUpperCase();
const code = this.codeManager[codeKey];
if (code) {
if (code.paramType == "kv:number") {
const dic: Record<string, number> = {};
for (const i of columns.slice(1)) {
const match = i.match(/([a-zA-Z]+)(\d+)/);
if (match) {
dic[match[1].toLowerCase()] = Number(match[2]);
}
}
result += code.exec(dic);
} else {
result += code.exec(...columns.slice(1));
}
} else {
console.log(codeKey + '不支持')
}
}
return result;
}
}