Skip to main content

Formatters

formatCurrency

Formats a number as currency with proper localization.

Parameters

amount
number
required
The amount to format
options
CurrencyFormatOptions
Formatting options

Return Value

formatted
string
Formatted currency string

Example

import { formatCurrency } from '@/utils/formatters';

formatCurrency(1234.56); // "$1,234.56"
formatCurrency(1234.56, { currency: 'EUR', locale: 'de-DE' }); // "1.234,56 €"
formatCurrency(1234.5, { decimals: 0 }); // "$1,235"

formatDate

Formats a date according to specified format and locale.

Parameters

date
Date | string | number
required
The date to format (Date object, ISO string, or timestamp)
format
DateFormat
default:"'medium'"
Format preset: ‘short’, ‘medium’, ‘long’, ‘full’, or custom format string
options
DateFormatOptions
Additional formatting options

Return Value

formatted
string
Formatted date string

Example

import { formatDate } from '@/utils/formatters';

const date = new Date('2024-03-15T14:30:00Z');

formatDate(date); // "Mar 15, 2024"
formatDate(date, 'long'); // "March 15, 2024"
formatDate(date, 'short', { includeTime: true }); // "3/15/24, 2:30 PM"
formatDate(date, 'YYYY-MM-DD'); // "2024-03-15"
formatDate(date, 'medium', { locale: 'fr-FR' }); // "15 mars 2024"

formatFileSize

Formats bytes into human-readable file size.

Parameters

bytes
number
required
Number of bytes
decimals
number
default:"2"
Number of decimal places

Return Value

formatted
string
Formatted file size (e.g., “1.5 MB”)

Example

import { formatFileSize } from '@/utils/formatters';

formatFileSize(1024); // "1.00 KB"
formatFileSize(1536, 0); // "2 KB"
formatFileSize(1048576); // "1.00 MB"
formatFileSize(1234567890); // "1.15 GB"

formatPhoneNumber

Formats a phone number string according to regional standards.

Parameters

phoneNumber
string
required
Phone number string (digits only or with formatting)
countryCode
string
default:"'US'"
ISO 3166-1 alpha-2 country code

Return Value

formatted
string
Formatted phone number

Example

import { formatPhoneNumber } from '@/utils/formatters';

formatPhoneNumber('5551234567'); // "(555) 123-4567"
formatPhoneNumber('5551234567', 'US'); // "(555) 123-4567"
formatPhoneNumber('2079460123', 'GB'); // "020 7946 0123"

Validators

validateEmail

Validates an email address format.

Parameters

email
string
required
Email address to validate

Return Value

isValid
boolean
Whether the email is valid

Example

import { validateEmail } from '@/utils/validators';

validateEmail('[email protected]'); // true
validateEmail('invalid.email'); // false
validateEmail('user@domain'); // false

validatePassword

Validates password strength against configurable rules.

Parameters

password
string
required
Password to validate
requirements
PasswordRequirements
Password strength requirements

Return Value

result
ValidationResult
Validation result object

Example

import { validatePassword } from '@/utils/validators';

validatePassword('Pass123!');
// { isValid: true, errors: [], strength: 'strong' }

validatePassword('weak');
// { 
//   isValid: false, 
//   errors: ['Must be at least 8 characters', 'Must contain a number'],
//   strength: 'weak'
// }

validatePassword('simple123', { requireSpecialChars: false });
// { isValid: true, errors: [], strength: 'medium' }

validateURL

Validates a URL format.

Parameters

url
string
required
URL to validate
options
URLValidationOptions
Validation options

Return Value

isValid
boolean
Whether the URL is valid

Example

import { validateURL } from '@/utils/validators';

validateURL('https://example.com'); // true
validateURL('not-a-url'); // false
validateURL('ftp://files.com', { allowedProtocols: ['ftp'] }); // true

Data Manipulation

debounce

Creates a debounced function that delays execution.

Parameters

func
Function
required
The function to debounce
delay
number
required
Delay in milliseconds

Return Value

debouncedFunc
Function & { cancel: () => void }
Debounced function with a cancel method

Example

import { debounce } from '@/utils/helpers';

const handleSearch = debounce((query: string) => {
  console.log('Searching for:', query);
}, 500);

// Only executes once after 500ms of no calls
handleSearch('a');
handleSearch('ab');
handleSearch('abc'); // Only this will execute

// Cancel pending execution
handleSearch.cancel();

throttle

Creates a throttled function that executes at most once per interval.

Parameters

func
Function
required
The function to throttle
interval
number
required
Interval in milliseconds

Return Value

throttledFunc
Function
Throttled function

Example

import { throttle } from '@/utils/helpers';

const handleScroll = throttle(() => {
  console.log('Scroll position:', window.scrollY);
}, 200);

window.addEventListener('scroll', handleScroll);

deepClone

Creates a deep copy of an object or array.

Parameters

value
T
required
Value to clone

Return Value

cloned
T
Deep cloned copy of the value

Example

import { deepClone } from '@/utils/helpers';

const original = { name: 'John', address: { city: 'NYC' } };
const cloned = deepClone(original);

cloned.address.city = 'LA';
console.log(original.address.city); // "NYC" (unchanged)

groupBy

Groups array items by a specified key or function.

Parameters

array
T[]
required
Array to group
keyOrFn
keyof T | ((item: T) => string)
required
Property key or function to group by

Return Value

grouped
Record<string, T[]>
Object with grouped items

Example

import { groupBy } from '@/utils/helpers';

const users = [
  { name: 'Alice', role: 'admin' },
  { name: 'Bob', role: 'user' },
  { name: 'Charlie', role: 'admin' }
];

const byRole = groupBy(users, 'role');
// {
//   admin: [{ name: 'Alice', role: 'admin' }, { name: 'Charlie', role: 'admin' }],
//   user: [{ name: 'Bob', role: 'user' }]
// }

const byFirstLetter = groupBy(users, user => user.name[0]);
// {
//   A: [{ name: 'Alice', role: 'admin' }],
//   B: [{ name: 'Bob', role: 'user' }],
//   C: [{ name: 'Charlie', role: 'admin' }]
// }

sortBy

Sorts array by specified key or comparator function.

Parameters

array
T[]
required
Array to sort
keyOrFn
keyof T | ((item: T) => any)
required
Property key or comparator function
order
'asc' | 'desc'
default:"'asc'"
Sort order

Return Value

sorted
T[]
New sorted array (original unchanged)

Example

import { sortBy } from '@/utils/helpers';

const products = [
  { name: 'Phone', price: 699 },
  { name: 'Laptop', price: 1299 },
  { name: 'Tablet', price: 499 }
];

const byPrice = sortBy(products, 'price');
// [{ name: 'Tablet', price: 499 }, { name: 'Phone', price: 699 }, ...]

const byPriceDesc = sortBy(products, 'price', 'desc');
// [{ name: 'Laptop', price: 1299 }, { name: 'Phone', price: 699 }, ...]

const byName = sortBy(products, p => p.name.toLowerCase());

String Utilities

truncate

Truncates a string to a maximum length.

Parameters

str
string
required
String to truncate
maxLength
number
required
Maximum length
suffix
string
default:"'...'"
Suffix to append when truncated

Return Value

truncated
string
Truncated string

Example

import { truncate } from '@/utils/helpers';

truncate('Hello World', 8); // "Hello..."
truncate('Hello', 10); // "Hello"
truncate('Hello World', 8, '…'); // "Hello W…"

capitalize

Capitalizes the first letter of a string.

Parameters

str
string
required
String to capitalize

Return Value

capitalized
string
Capitalized string

Example

import { capitalize } from '@/utils/helpers';

capitalize('hello world'); // "Hello world"
capitalize('HELLO'); // "Hello"

slugify

Converts a string to a URL-friendly slug.

Parameters

str
string
required
String to slugify

Return Value

slug
string
URL-friendly slug

Example

import { slugify } from '@/utils/helpers';

slugify('Hello World!'); // "hello-world"
slugify('React & TypeScript'); // "react-typescript"
slugify('  Multiple   Spaces  '); // "multiple-spaces"

Build docs developers (and LLMs) love