feat(ui): add pluralize utility function
Handles irregular plurals, measurement units that stay singular, and standard English pluralization rules.
This commit is contained in:
parent
159755af8d
commit
5982abfb05
1 changed files with 22 additions and 0 deletions
|
|
@ -4,3 +4,25 @@ import { twMerge } from "tailwind-merge"
|
||||||
export function cn(...inputs: ClassValue[]) {
|
export function cn(...inputs: ClassValue[]) {
|
||||||
return twMerge(clsx(inputs))
|
return twMerge(clsx(inputs))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const IRREGULAR: Record<string, string> = {
|
||||||
|
person: "people",
|
||||||
|
child: "children",
|
||||||
|
man: "men",
|
||||||
|
woman: "women",
|
||||||
|
};
|
||||||
|
|
||||||
|
const NO_PLURAL = new Set([
|
||||||
|
"kg", "g", "mg", "mcg", "l", "ml", "cl", "dl",
|
||||||
|
"m", "cm", "mm", "km", "tick", "hertz", "hz",
|
||||||
|
]);
|
||||||
|
|
||||||
|
export function pluralize(amount: number, unit: string): string {
|
||||||
|
if (amount === 1) return unit;
|
||||||
|
const lower = unit.toLowerCase();
|
||||||
|
if (NO_PLURAL.has(lower) || unit.endsWith("s")) return unit;
|
||||||
|
if (IRREGULAR[lower]) return IRREGULAR[lower];
|
||||||
|
if (/[^aeiou]y$/i.test(unit)) return unit.slice(0, -1) + "ies";
|
||||||
|
if (/[sxz]$/i.test(unit) || /(sh|ch)$/i.test(unit)) return unit + "es";
|
||||||
|
return unit + "s";
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue