拒绝检查、首个匹配与顺序处理
使用真实清单表达多项检查和枚举分发;单个普通判断仍可直接使用 if。
breakWhile(occur,error?) 在遭遇拒绝条件时抛错;省略原因时创建 Error。检查数组按顺序在第一项拒绝后停止,依赖前项校验的条件使用回调,原因工厂仅在拒绝时执行。数组字段仍统一叫 occur,不按单复数另造 conditions。
注意:直接传 breakWhile(() => bad) 时,函数本身被当作一个真值,并不会求值;需要惰性条件时使用检查对象 {occur:()=>bad} 或谓词数组 [()=>bad]。
matchRule 返回首个匹配 handler 的结果,即使结果是 undefined 也不继续。walkRules 顺序执行所有匹配项,后项可观察前项修改;两者谓词同步返回 boolean。单条件正常处理不必套壳为清单。
由简到繁的同业务示例
一个明确的拒绝
入门 · Node.js
ts
import { Support } from '@jangts/agent-core';
const input = '你好';
Support.breakWhile(!input.trim(), '问题不能为空');
console.log(input);js
import { Support } from '@jangts/agent-core';
const input = '你好';
Support.breakWhile(!input.trim(), '问题不能为空');
console.log(input);有依赖关系的检查按序求值
配置 · Node.js
ts
import { Support } from '@jangts/agent-core';
const input: unknown = { name: 'Ivan' };
Support.breakWhile([
{ occur: !input || typeof input !== 'object', error: '需要对象' },
{ occur: () => !('name' in (input as object)), error: '缺少 name' },
]);
console.log(input);js
import { Support } from '@jangts/agent-core';
const input = { name: 'Ivan' };
Support.breakWhile([
{ occur: !input || typeof input !== 'object', error: '需要对象' },
{ occur: () => !('name' in input), error: '缺少 name' },
]);
console.log(input);声明式优先分发与顺序转换
扩展 · Node.js
ts
import { Support } from '@jangts/agent-core';
const routeName = Support.matchRule([
{ id: 'status', description: '状态意图', pattern: (input: string) => input === 'status', handle: () => 'service' },
{ id: 'fallback', description: '其他意图', handle: () => 'reply' },
], 'status');
const state = { answer: ' 服务正常 ' };
Support.walkRules([
{ handle: (value: typeof state) => { value.answer = value.answer.trim(); } },
{ pattern: (value: typeof state) => !!value.answer, handle: value => { value.answer += '。'; } },
], state);
console.log(routeName, state.answer);js
import { Support } from '@jangts/agent-core';
const routeName = Support.matchRule([
{ id: 'status', description: '状态意图', pattern: (input) => input === 'status', handle: () => 'service' },
{ id: 'fallback', description: '其他意图', handle: () => 'reply' },
], 'status');
const state = { answer: ' 服务正常 ' };
Support.walkRules([
{ handle: (value) => { value.answer = value.answer.trim(); } },
{ pattern: (value) => !!value.answer, handle: value => { value.answer += '。'; } },
], state);
console.log(routeName, state.answer);