datezone
Version:
A lightweight and comprehensive date and timeZone utility library for JavaScript.
57 lines • 2.14 kB
JavaScript
import { getCachedNumberFormat } from "./number-format-cache.js";
const ordinalSuffixes = {
de: { other: "." },
en: { few: "rd", one: "st", other: "th", two: "nd" },
es: { other: "º" }, // Spanish uses º for ordinals
fr: { one: "er", other: "e" }, // German uses period
it: { one: "º", other: "º" }, // Italian
nl: { other: "e" }, // Portuguese
pt: { one: "º", other: "º" }, // Dutch
// Languages without suffixes (ru, ja, zh, etc.) are omitted and will return empty string
};
const pluralRulesCache = new Map();
function getPluralRules(locale) {
if (!pluralRulesCache.has(locale)) {
try {
pluralRulesCache.set(locale, new Intl.PluralRules(locale, { type: "ordinal" }));
}
catch {
// Fall back to English for invalid locales
pluralRulesCache.set(locale, new Intl.PluralRules("en", { type: "ordinal" }));
}
}
return pluralRulesCache.get(locale);
}
function getOrdinalSuffix(locale, rule) {
// Try exact locale first
if (ordinalSuffixes[locale]?.[rule]) {
return ordinalSuffixes[locale][rule];
}
// Try language part of locale (e.g., 'en' from 'en-US')
const language = locale.split("-")[0];
if (language && language !== locale && ordinalSuffixes[language]?.[rule]) {
return ordinalSuffixes[language][rule];
}
// Fall back to empty string for unsupported locales
return "";
}
/**
* Format ordinal.
*
* @param number - The number to format.
* @param locale - The locale to use.
* @returns The ordinal suffix.
* @see https://datezone.dev/docs/reference/ordinal#formatordinal
*/
export function formatOrdinal(number, locale = "en") {
const pr = getPluralRules(locale);
// For unsupported locales, use Western numerals
const numberingSystem = ["ar", "fa", "ur"].includes(locale)
? "latn"
: undefined;
const nf = getCachedNumberFormat(locale, { numberingSystem });
const rule = pr.select(number);
const suffix = getOrdinalSuffix(locale, rule);
return `${nf.format(number)}${suffix}`;
}
//# sourceMappingURL=ordinal.pub.js.map