实现说明
示例脉络清晰围绕着核心函数 formatOrdinal组织。
使用要点
- 工具链自带的东西就够跑——无需额外安装。
- 演示输出是带标签的(
ordinals:、rule for 11:),每个操作都会留下自己的一行标注。
常见问题
依赖情况复杂吗?
一点也不复杂:零依赖,没有要锁版本或审计的东西。 文件在加载时定义 formatOrdinal。
主签名形如 function formatOrdinal(n: number, suffixes: OrdinalSuffixTable = EN_ORDINALS)
核心语句
const suffix = suffixes[category] ?? suffixes.other;
return `${n}${suffix}`;
代码示例
// Require 'other' as a guaranteed fallback while keeping locale-specific rules optional
type OrdinalSuffixTable = Record<'other', string> &
Partial<Record<Intl.LDMLPluralRule, string>>;
const EN_ORDINALS: OrdinalSuffixTable = {
one: 'st',
two: 'nd',
few: 'rd',
other: 'th',
};
const ordinalRules = new Intl.PluralRules('en-US', { type: 'ordinal' });
function formatOrdinal(n: number, suffixes: OrdinalSuffixTable = EN_ORDINALS): string {
const category = ordinalRules.select(n);
const suffix = suffixes[category] ?? suffixes.other;
return `${n}${suffix}`;
}
const sampleRanks = [1, 2, 3, 4, 11, 12, 21, 22, 103];
console.log('ordinals:', sampleRanks.map((n) => formatOrdinal(n)).join(', '));
console.log('rule for 11:', ordinalRules.select(11), '| rule for 23:', ordinalRules.select(23));