Intl.PluralRules Ordinal Tables With Types
Pair Intl.PluralRules ordinal selection with a typed lookup table requiring an other fallback so rank formatting handles 1st, 2nd, 3rd, and 11th accurately.
Code
// 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));Output
Captured from a sandboxed run of this snippet in the build pipeline.
ordinals: 1st, 2nd, 3rd, 4th, 11th, 12th, 21st, 22nd, 103rd
rule for 11: other | rule for 23: fewHow it works
Everything executes inside the dedicated routine formatOrdinal.
Watch out for
- The imports (if any) point only at standard-library modules.
Putting it to use
Entry signature: function formatOrdinal(n: number, suffixes: OrdinalSuffixTable = EN_ORDINALS)
The run emits 2 labeled sections — ordinals:, rule for 11: — one per step.
Core lines
const suffix = suffixes[category] ?? suffixes.other;
return `${n}${suffix}`;
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit. The file defines `formatOrdinal` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.