import dayjs from 'dayjs'; import size from 'lodash/size'; interface SpecialColors { [index: number]: string; } /** * Formats the number as currency, for example -10590 converts to "$10.59k". * @param value * @returns string */ const formatCurrency = (value?: number) => { if (!value) { return value === 0 ? '0' : '-'; } if (value < 0) value *= -1; if (value >= 100 && value < 1000000) { return `$${Math.round((value / 1000 + Number.EPSILON) * 100) / 100}k`; } else if (value >= 1000000 && value < 1000000000) { return `$${Math.round((value / 1000000 + Number.EPSILON) * 100) / 100}m`; } else if (value >= 1000000000) { return `$${Math.round((value / 1000000000 + Number.EPSILON) * 100) / 100}b`; } else { return `$${value}`; } }; /** * Converts a date-time string to a formatted date using the dayjs library. * @param value * @param format * @returns */ const formatDate = (value: string | Date, format = 'MMM DD, YYYY') => dayjs(value).format(format); /** * Converts a company size string to a human-readable value. * @param size * @returns */ const sizeToCompany = (size?: string) => { if (size) { switch (size.toLowerCase()) { case 'small': { return 'Small (0 < 50)'; } case 'smb': { return 'SMB (0 < 50)'; } case 'medium': { return 'Medium (50 < 200)'; } case 'large': { return 'Large (200 < 1000)'; } case 'enterprise': { return 'Enterprise (1000+)'; } default: return size; } } return 'NA'; }; /** * Converts a username string to initials and color for user avatar. * @param userName * @param specialColors * @param alwaysTwoLetters Always return two-letter initials? * @returns */ const userNameToInitials = ( userName: string, specialColors?: SpecialColors, alwaysTwoLetters = false ) => { const split = userName.split(' '); const first = split[0][0] || ''; const second = split[1]?.[0] || (alwaysTwoLetters ? first : ''); const initials = first + second; const specialColorsCount = specialColors && size(specialColors); const letterToCode = (letter?: string) => (letter && parseInt(letter, 36)) || 0; const color = specialColors && specialColorsCount ? specialColors[ ((letterToCode(first) + letterToCode(second)) % specialColorsCount) + 1 ] : ''; return { color, first, initials, second }; }; const trimSpaces = (text: string | undefined) => text ? text.replace(/\s/g, '') : undefined; export { formatCurrency, formatDate, sizeToCompany, userNameToInitials, trimSpaces };