UNPKG

frontix

Version:

Modern utility toolkit for frontend developers — 25+ utilities for strings, dates, validation, async operations, deep objects, and more. TypeScript-first, tree-shakable, and lightweight. Includes debounce, throttle, deep cloning, date formatting, validati

478 lines (456 loc) 15.3 kB
import dayjs from 'dayjs'; /** * Truncates a string to a specified length with an optional custom suffix. * * @param str - The input string to truncate * @param length - The maximum length of the truncated string (excluding suffix) * @param suffix - The suffix to append when truncating (default: "...") * @returns The truncated string with suffix if truncated, or the original string if no truncation needed * * @example * ```typescript * truncate("Hello World", 5); // "Hello..." * truncate("Short", 10); // "Short" * truncate("Very Long Text", 7, "~"); // "Very Lo~" * ``` */ declare function truncate(str: string, length: number, suffix?: string): string; /** * Safely converts a value to a number with fallback to 0. * * @param value - The value to convert (string, number, or any other type) * @returns A number, or 0 if the conversion fails * * @example * ```typescript * toNumber("42"); // 42 * toNumber("abc"); // 0 * toNumber(123); // 123 * toNumber(null); // 0 * toNumber(undefined); // 0 * ``` */ declare function toNumber(value: unknown): number; /** * Safely converts a value to a string with fallback to empty string. * * @param value - The value to convert (string, number, or any other type) * @returns A string representation of the value, or empty string if null/undefined * * @example * ```typescript * toString(42); // "42" * toString("hello"); // "hello" * toString(null); // "" * toString(undefined); // "" * ``` */ declare function toString(value: unknown): string; /** * Converts an array to dropdown-friendly objects with label and value properties. * * @param arr - The input array to convert * @returns An array of objects with `label` and `value` properties * * @example * ```typescript * toDropdown(["Apple", "Banana"]); * // Returns: [{ label: "Apple", value: "Apple" }, { label: "Banana", value: "Banana" }] * * toDropdown([1, 2, 3]); * // Returns: [{ label: 1, value: 1 }, { label: 2, value: 2 }, { label: 3, value: 3 }] * ``` */ declare function toDropdown<T>(arr: T[]): { label: T; value: T; }[]; /** * Formats a date with custom format and locale support. * * @param date - The date to format (string, Date object, or dayjs object) * @param format - The format string (default: "DD/MM/YYYY") * @param locale - The locale for formatting (default: "en") * @returns Formatted date string * * @example * ```typescript * formatDate("2025-01-15"); // "15/01/2025" * formatDate("2025-01-15", "MMMM D, YYYY"); // "January 15, 2025" * formatDate("2025-01-15", "DD/MM/YYYY", "fr"); // "15/01/2025" * ``` */ declare function formatDate(date: string | Date | dayjs.Dayjs, format?: string, locale?: string): string; /** * Creates a debounced function that delays invoking the provided function * until after the specified wait time has elapsed since the last time it was invoked. * * @param func - The function to debounce * @param wait - The number of milliseconds to delay * @returns A debounced version of the provided function * * @example * ```typescript * const debouncedSearch = debounce((query) => { * console.log("Searching for:", query); * }, 300); * * // Only the last call will execute after 300ms * debouncedSearch("a"); * debouncedSearch("ab"); * debouncedSearch("abc"); // Only this will execute * ``` */ declare function debounce<T extends (...args: unknown[]) => void>(func: T, wait: number): (...args: Parameters<T>) => void; /** * Replaces null, undefined, or empty string values with a fallback value. * Useful for displaying "N/A" or "---" in UI components. * * @param value - The value to check * @param fallback - The fallback value to use if the original is null/undefined/empty * @returns The original value if valid, otherwise the fallback value * * @example * ```typescript * safeValue(null, "N/A"); // "N/A" * safeValue(undefined, "---"); // "---" * safeValue("", "Empty"); // "Empty" * safeValue("Hello", "World"); // "Hello" * safeValue(42, "N/A"); // 42 * ``` */ declare function safeValue<T>(value: T, fallback: T): T; /** * Validates an email address format. * Uses a comprehensive regex pattern to check email validity. * * @param email - The email address to validate * @returns true if the email format is valid, false otherwise * * @example * ```typescript * validateEmail("user@example.com"); // true * validateEmail("invalid-email"); // false * validateEmail(""); // false * validateEmail("user@domain.co.uk"); // true * ``` */ declare function validateEmail(email: string): boolean; /** * Validates a phone number format. * Supports international formats and common patterns. * * @param phone - The phone number to validate * @returns true if the phone number format is valid, false otherwise * * @example * ```typescript * validatePhone("+1-555-123-4567"); // true * validatePhone("555-123-4567"); // true * validatePhone("(555) 123-4567"); // true * validatePhone("555.123.4567"); // true * validatePhone("invalid"); // false * ``` */ declare function validatePhone(phone: string): boolean; /** * Retries a failed async function with configurable retry attempts and delay. * Useful for handling network failures or temporary errors. * * @param fn - The async function to retry * @param retries - Maximum number of retry attempts (default: 3) * @param delay - Base delay between retries in milliseconds (default: 1000) * @returns Promise that resolves with the function result or rejects after all retries * * @example * ```typescript * const fetchData = retry(async () => { * const response = await fetch('/api/data'); * if (!response.ok) throw new Error('Failed to fetch'); * return response.json(); * }, 3, 2000); * ``` */ declare function retry<T>(fn: () => Promise<T>, retries?: number, delay?: number): Promise<T>; /** * Executes a function with a timeout. If the function doesn't complete within * the specified time, it rejects with a timeout error. * * @param fn - The async function to execute * @param ms - Timeout in milliseconds * @returns Promise that resolves with the function result or rejects on timeout * * @example * ```typescript * const result = await timeout( * async () => await fetch('/api/slow-endpoint'), * 5000 * ); * ``` */ declare function timeout<T>(fn: () => Promise<T>, ms: number): Promise<T>; /** * Throttles function calls to a maximum frequency. * Ensures the function is called at most once per specified time interval. * * @param fn - The function to throttle * @param ms - Minimum time interval between function calls in milliseconds * @returns A throttled version of the function * * @example * ```typescript * const throttledScroll = throttle(() => { * console.log('Scroll event throttled'); * }, 100); * * window.addEventListener('scroll', throttledScroll); * ``` */ declare function throttle<T extends (...args: any[]) => any>(fn: T, ms: number): (...args: Parameters<T>) => void; /** * Creates a deep clone of an object, handling circular references. * Supports primitives, objects, arrays, dates, and other built-in types. * * @param obj - The object to clone * @returns A deep clone of the object * * @example * ```typescript * const original = { a: 1, b: { c: 2 } }; * const cloned = deepClone(original); * cloned.b.c = 3; * console.log(original.b.c); // 2 (unchanged) * ``` */ declare function deepClone<T>(obj: T, visited?: WeakMap<object, any>): T; /** * Performs a deep equality comparison between two values. * Handles objects, arrays, dates, and other complex types. * * @param a - First value to compare * @param b - Second value to compare * @returns true if the values are deeply equal, false otherwise * * @example * ```typescript * isEqual({ a: 1, b: { c: 2 } }, { a: 1, b: { c: 2 } }); // true * isEqual([1, 2, 3], [1, 2, 3]); // true * isEqual(new Date('2023-01-01'), new Date('2023-01-01')); // true * isEqual({ a: 1 }, { a: 2 }); // false * ``` */ declare function isEqual(a: any, b: any): boolean; /** * Deeply merges multiple objects, with later objects taking precedence. * Handles nested objects, arrays, and preserves non-object values. * * @param target - The target object to merge into * @param sources - Source objects to merge from * @returns The merged object * * @example * ```typescript * const obj1 = { a: 1, b: { c: 2 } }; * const obj2 = { b: { d: 3 }, e: 4 }; * const merged = merge(obj1, obj2); * // Result: { a: 1, b: { c: 2, d: 3 }, e: 4 } * ``` */ declare function merge<T extends Record<string, any>>(target: T, ...sources: Partial<T>[]): T; /** * Converts a date to a human-readable relative time string. * Shows time differences like "5 minutes ago", "2 hours ago", etc. * * @param date - The date to convert * @param now - Reference date (defaults to current time) * @returns Human-readable relative time string * * @example * ```typescript * timeAgo(new Date('2023-01-01T10:00:00Z')); // "2 years ago" * timeAgo(Date.now() - 300000); // "5 minutes ago" * timeAgo(Date.now() + 86400000); // "in 1 day" * ``` */ declare function timeAgo(date: Date | number, now?: Date | number): string; /** * Converts a date to a specific timezone. * Returns the date in the target timezone with proper formatting. * * @param date - The date to convert * @param timeZone - The target timezone (e.g., 'America/New_York', 'Europe/London') * @param options - Intl.DateTimeFormatOptions for formatting * @returns Formatted date string in the target timezone * * @example * ```typescript * toTimeZone(new Date(), 'America/New_York'); // "1/15/2024, 10:30:00 AM EST" * toTimeZone(new Date(), 'Europe/London', { * dateStyle: 'full' * }); // "Monday, January 15, 2024" * ``` */ declare function toTimeZone(date: Date | number, timeZone: string, options?: Intl.DateTimeFormatOptions): string; /** * Date comparison utility functions for common date checks. * Provides easy ways to check if dates fall within specific time periods. */ /** * Checks if a date is today. * * @param date - The date to check * @returns true if the date is today, false otherwise * * @example * ```typescript * isToday(new Date()); // true * isToday(new Date('2023-01-01')); // false * ``` */ declare function isToday(date: Date | number): boolean; /** * Checks if a date is yesterday. * * @param date - The date to check * @returns true if the date is yesterday, false otherwise * * @example * ```typescript * const yesterday = new Date(); * yesterday.setDate(yesterday.getDate() - 1); * isYesterday(yesterday); // true * ``` */ declare function isYesterday(date: Date | number): boolean; /** * Checks if a date is within the current week. * * @param date - The date to check * @returns true if the date is within the current week, false otherwise * * @example * ```typescript * isThisWeek(new Date()); // true * isThisWeek(new Date('2023-01-01')); // false * ``` */ declare function isThisWeek(date: Date | number): boolean; /** * Checks if a date is within the current month. * * @param date - The date to check * @returns true if the date is within the current month, false otherwise * * @example * ```typescript * isThisMonth(new Date()); // true * isThisMonth(new Date('2023-01-01')); // false * ``` */ declare function isThisMonth(date: Date | number): boolean; /** * Checks if a date is within the current year. * * @param date - The date to check * @returns true if the date is within the current year, false otherwise * * @example * ```typescript * isThisYear(new Date()); // true * isThisYear(new Date('2023-01-01')); // false * ``` */ declare function isThisYear(date: Date | number): boolean; /** * Converts a string to a URL-friendly slug. * Removes special characters, converts spaces to hyphens, and makes lowercase. * * @param str - The string to convert * @param separator - Character to use as separator (default: '-') * @returns URL-friendly slug string * * @example * ```typescript * slugify("Hello World!"); // "hello-world" * slugify("User's Profile", '_'); // "users_profile" * slugify("Café & Résumé"); // "cafe-resume" * ``` */ declare function slugify(str: string, separator?: string): string; /** * Capitalizes the first letter of a string. * Optionally capitalizes all words in the string. * * @param str - The string to capitalize * @param allWords - Whether to capitalize all words (default: false) * @returns Capitalized string * * @example * ```typescript * capitalize("hello world"); // "Hello world" * capitalize("hello world", true); // "Hello World" * capitalize("JOHN DOE", true); // "John Doe" * ``` */ declare function capitalize(str: string, allWords?: boolean): string; /** * String case conversion utility functions. * Provides various ways to convert strings between different case formats. */ /** * Converts a string to camelCase. * * @param str - The string to convert * @returns camelCase string * * @example * ```typescript * camelCase("hello world"); // "helloWorld" * camelCase("user-name"); // "userName" * camelCase("first_name_last_name"); // "firstNameLastName" * ``` */ declare function camelCase(str: string): string; /** * Converts a string to kebab-case. * * @param str - The string to convert * @returns kebab-case string * * @example * ```typescript * kebabCase("helloWorld"); // "hello-world" * kebabCase("userName"); // "user-name" * kebabCase("firstNameLastName"); // "first-name-last-name" * ``` */ declare function kebabCase(str: string): string; /** * Converts a string to snake_case. * * @param str - The string to convert * @returns snake_case string * * @example * ```typescript * snakeCase("helloWorld"); // "hello_world" * snakeCase("userName"); // "user_name" * snakeCase("firstNameLastName"); // "first_name_last_name" * ``` */ declare function snakeCase(str: string): string; /** * Converts a string to PascalCase. * * @param str - The string to convert * @returns PascalCase string * * @example * ```typescript * pascalCase("hello world"); // "HelloWorld" * pascalCase("user-name"); // "UserName" * pascalCase("first_name_last_name"); // "FirstNameLastName" * ``` */ declare function pascalCase(str: string): string; export { camelCase, capitalize, debounce, deepClone, formatDate, isEqual, isThisMonth, isThisWeek, isThisYear, isToday, isYesterday, kebabCase, merge, pascalCase, retry, safeValue, slugify, snakeCase, throttle, timeAgo, timeout, toDropdown, toNumber, toString, toTimeZone, truncate, validateEmail, validatePhone };