实现说明
stages、and、or、unit 定义在模块顶层,中间不经过函数作用域。
使用要点
- 演示输出是带标签的(
narrow :),每个操作都会留下自己的一行标注。
常见问题
运行时需要 npm、pip、cargo 之类帮忙吗?
不需要——包管理器在这里无事可做,没有任何声明。 状态都挂在模块顶层:stages、and、or。
核心语句
.map((part) => (part.type === 'literal' ? `[${part.value.trim()}]` : part.value))
.join('');
const and = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
const or = new Intl.ListFormat('en', { style: 'long', type: 'disjunction' });
代码示例
// Intl.ListFormat: 把数组渲染成符合语言习惯的列表文案
const stages = ['parse-args', 'run-pipeline', 'write-report'];
// conjunction(long 风格): "a, b, and c"
const and = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
console.log('long :', and.format(stages));
// disjunction: "a, b, or c"——错误提示里列举可选值
const or = new Intl.ListFormat('en', { style: 'long', type: 'disjunction' });
console.log('or :', or.format(['json', 'yaml', 'toml']));
// narrow + unit: 空间紧张时的紧凑形态
const unit = new Intl.ListFormat('en', { style: 'narrow', type: 'unit' });
console.log('narrow :', unit.format(['3 files', '2 warnings']));
// formatToParts: 拿到底层分段,自定义包裹样式
const marked = and
.formatToParts(stages)
.map((part) => (part.type === 'literal' ? `[${part.value.trim()}]` : part.value))
.join('');
console.log('parts :', marked);