Skip to content

Instantly share code, notes, and snippets.

@goofballLogic
Last active October 29, 2021 09:57
Show Gist options
  • Save goofballLogic/c81644000e9555f8001424838ef83f6f to your computer and use it in GitHub Desktop.
Save goofballLogic/c81644000e9555f8001424838ef83f6f to your computer and use it in GitHub Desktop.
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