Skip to content

Instantly share code, notes, and snippets.

@goofballLogic
Created October 28, 2021 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goofballLogic/799a2ba528914b14ea22fb4f836f7fcd to your computer and use it in GitHub Desktop.
Save goofballLogic/799a2ba528914b14ea22fb4f836f7fcd to your computer and use it in GitHub Desktop.
const ordinalSuffixes = {
"one": "st",
"two": "nd",
"few": "rd",
"other": "th"
};
const ordinalPluralRules = new Intl.PluralRules("en", { type: "ordinal" });
function withOrdinalSuffix(x) {
if(typeof x != "number") throw new TypeError(`Expected Number but received ${typeof x}`);
if(x < 1) throw new RangeError(`Expected a number > 0 but received ${x}`);
const ordinal = ordinalPluralRules.select(x);
if (!ordinal in ordinalSuffixes) throw new Error(`Unexpected ordinal ${ordinal}`);
const suffix = ordinalSuffixes[ordinal];
return `${x}${suffix}`;
}
withOrdinalSuffix(28) // 28th
withOrdinalSuffix(1) // 1st
withOrdinalSuffix(2) // 2nd
withOrdinalSuffix(3) // 3rd
withOrdinalSuffix(4) // 4th
withOrdinalSuffix(5) // 5th
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment