Skip to content

Instantly share code, notes, and snippets.

@none23
Created July 22, 2020 07:42
Show Gist options
  • Save none23/7bbd27dc9dc6fb15385e627420961e1a to your computer and use it in GitHub Desktop.
Save none23/7bbd27dc9dc6fb15385e627420961e1a to your computer and use it in GitHub Desktop.
plurals
const { abs } = Math;
const { isNaN } = Number;
const NBSP = " ";
export function plural(one: string, two?: Maybe<string>, five?: Maybe<string>) {
return (quantiry: Maybe<number>) =>
pluralize(absInt(number), [one, two ?? one, five ?? two ?? one]);
}
function nbspJoin<T = number | string>(...arr: T[]): string {
return arr.join(NBSP);
}
function absInt(number: number): undefined | number {
const int = abs(parseInt(number, 10));
return isNaN(int) ? undefined : int;
}
function pluralize(int: number, ...declensions: string[]): string {
return declensions[
int % 100 > 4 && int % 100 < 20
? 2
: [2, 0, 1, 1, 1, 2][int % 10 < 5 ? int % 10 : 5]
];
}
export function format(
formatter: <T = any>(quantiry: number, unit: string) => T
) {
return (one: string, two?: string, five?: string) => (number: number) =>
formatter(number, plural(one, two, five)(number));
}
const defaultFormat = format(nbspJoin);
export default defaultFormat;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment