Created
October 28, 2021 17:28
-
-
Save goofballLogic/799a2ba528914b14ea22fb4f836f7fcd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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