Created
July 22, 2020 07:42
-
-
Save none23/7bbd27dc9dc6fb15385e627420961e1a to your computer and use it in GitHub Desktop.
plurals
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 { 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