Last active
October 29, 2021 09:57
-
-
Save goofballLogic/c81644000e9555f8001424838ef83f6f to your computer and use it in GitHub Desktop.
This file contains 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 = { | |
"en": { | |
"one": "st", | |
"two": "nd", | |
"few": "rd", | |
"other": "th" | |
} | |
}; | |
export class OrdinalFormat { | |
#rules; | |
#suffixes; | |
constructor(locale) { | |
if(!(locale in ordinalSuffixes)) throw new Error(`Unhandled locale: ${locale}`); | |
this.#suffixes = ordinalSuffixes[locale]; | |
this.#rules = new Intl.PluralRules(locale, { type: "ordinal" }); | |
} | |
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 = this.#rules.select(x); | |
if (!ordinal in this.#suffixes) throw new Error(`Unexpected ordinal ${ordinal}`); | |
const suffix = this.#suffixes[ordinal]; | |
return `${x}${suffix}`; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment