js-helper-fns
v4.0.0
Published
A comprehensive TypeScript utility library for frontend development, providing essential functions for string manipulation, date formatting, number formatting, array operations, object utilities, and validation.
Downloads
2
Maintainers
Readme
Hubtel Frontend Utils
A comprehensive TypeScript utility library for frontend development, providing essential functions for string manipulation, number formatting, and more.
Features
- 🎯 Type-safe - Written in TypeScript with full type definitions
- 🚀 Lightweight - Modular design, import only what you need
- 🧪 Well-tested - Comprehensive test coverage
- 📦 Tree-shakable - Optimized for modern bundlers
- 🌍 Internationalization - Built-in locale support for formatting
- 💼 Production-ready - Used in Hubtel's production applications
Installation
npm install @hubtel/utilsQuick Start
import { formatCurrency, slugify, isEmpty } from '@hubtel/utils';
// Format currency (defaults to GHS)
formatCurrency(1234.56); // "GH₵1,234.56"
// Create URL-friendly slugs
slugify('Hello World!'); // "hello-world"
// Check if values are empty
isEmpty([]); // true
isEmpty({ name: 'John' }); // falseAPI Reference
String Utilities
capitalize(str: string): string
Capitalizes the first letter of a string.
capitalize('hello world'); // "Hello world"
capitalize('HELLO WORLD'); // "Hello world"camelToKebab(str: string): string
Converts camelCase strings to kebab-case.
camelToKebab('firstName'); // "first-name"
camelToKebab('XMLHttpRequest'); // "xml-http-request"slugify(str: string, options?): string
Creates URL-friendly slugs from strings.
slugify('Hello World! 123'); // "hello-world-123"
slugify('Accént Chàrs', { separator: '_' }); // "accent_chars"truncate(str: string, length: number, suffix?: string): string
Truncates strings to a specified length.
truncate('Long text here', 10); // "Long text..."
truncate('Short', 10); // "Short"extractInitials(name: string, options?): string
Extracts initials from names.
extractInitials('John Doe'); // "JD"
extractInitials('Mary Jane Watson', { maxInitials: 2 }); // "MJ"pluralize(word: string, count: number, plural?: string): string
Pluralizes words based on count.
pluralize('item', 1); // "item"
pluralize('item', 2); // "items"
pluralize('child', 2, 'children'); // "children"Number Utilities
formatCurrency(value: number, options?): string
Formats numbers as currency with locale support.
formatCurrency(1234.56); // "GH₵1,234.56" (default GHS)
formatCurrency(1234.56, { currency: 'USD' }); // "$1,234.56"
formatCurrency(1234.56, { currency: 'JPY' }); // "¥1,235"formatNumber(value: number, options?): string
Formats numbers with various options.
formatNumber(1234.567); // "1,234.567"
formatNumber(1234.567, { decimals: 2 }); // "1,234.57"
formatNumber(0.1234, { percentage: true }); // "12.34%"formatCreditCardNumber(cardNumber: string | number, options?): string
Formats credit card numbers with proper spacing.
formatCreditCardNumber('4111111111111111'); // "4111 1111 1111 1111"
formatCreditCardNumber('371449635398431'); // "3714 496353 98431" (Amex)
formatCreditCardNumber('30569309025904'); // "3056 930902 5904" (Diners)clamp(value: number, min: number, max: number): number
Clamps a number between min and max values.
clamp(15, 0, 10); // 10
clamp(-5, 0, 10); // 0
clamp(5, 0, 10); // 5randomBetween(min: number, max: number): number
Generates random numbers between min and max.
randomBetween(1, 10); // Random number between 1 and 10
randomBetween(0, 1); // Random decimal between 0 and 1roundToNearest(value: number, nearest: number): number
Rounds numbers to the nearest specified value.
roundToNearest(23, 5); // 25
roundToNearest(12.34, 0.5); // 12.5Coming Soon
The following features are currently under development and will be available in future releases:
Date Utilities
- Date formatting with custom patterns
- Relative time strings
- Date manipulation functions
- Date validation functions
Array Utilities
- Array chunking
- Unique value filtering
- Array shuffling
- Sorting and grouping
- Array manipulation helpers
Object Utilities
- Deep cloning
- Object merging
- Property picking/omitting
- Object flattening
- Nested property access
Validation Utilities
- Email validation
- URL validation
- Number validation
- Data type checking
Function Reference
| Category | Function | Description | Parameters | Return Type |
|----------|----------|-------------|------------|-------------|
| String Utilities |
| | capitalize | Capitalizes the first letter of a string | str: string | string |
| | camelToKebab | Converts camelCase to kebab-case | str: string | string |
| | slugify | Creates URL-friendly slugs | str: string, options?: { separator?: string } | string |
| | truncate | Truncates string to specified length | str: string, length: number, suffix?: string | string |
| | extractInitials | Extracts initials from names | name: string, options?: { maxInitials?: number } | string |
| | pluralize | Pluralizes words based on count | word: string, count: number, plural?: string | string |
| Number Utilities |
| | formatCurrency | Formats numbers as currency | value: number, options?: { currency?: string, locale?: string, ... } | string |
| | formatNumber | Formats numbers with locale support | value: number, options?: { locale?: string, minimumFractionDigits?: number, ... } | string |
| | formatCreditCardNumber | Formats credit card numbers with spacing | cardNumber: string \| number, options?: { separator?: string } | string |
| | clamp | Clamps number between min and max | value: number, min: number, max: number | number |
| | randomBetween | Generates random number between range | min: number, max: number | number |
| | roundToNearest | Rounds to nearest specified value | value: number, nearest: number | number |
| Date Utilities |
| | formatDate | Formats date with custom pattern | date: DateInput, format?: string, locale?: string | string |
| | getRelativeTime | Gets relative time string | date: DateInput, baseDate?: DateInput, locale?: string | string |
| | addDays | Adds days to date | date: DateInput, days: number | Date |
| | addHours | Adds hours to date | date: DateInput, hours: number | Date |
| | addMinutes | Adds minutes to date | date: DateInput, minutes: number | Date |
| | addMonths | Adds months to date | date: DateInput, months: number | Date |
| | addYears | Adds years to date | date: DateInput, years: number | Date |
| | subtractDays | Subtracts days from date | date: DateInput, days: number | Date |
| | subtractHours | Subtracts hours from date | date: DateInput, hours: number | Date |
| | subtractMinutes | Subtracts minutes from date | date: DateInput, minutes: number | Date |
| | subtractMonths | Subtracts months from date | date: DateInput, months: number | Date |
| | subtractYears | Subtracts years from date | date: DateInput, years: number | Date |
| | isToday | Checks if date is today | date: DateInput | boolean |
| | isYesterday | Checks if date is yesterday | date: DateInput | boolean |
| | isTomorrow | Checks if date is tomorrow | date: DateInput | boolean |
| | isThisWeek | Checks if date is this week | date: DateInput | boolean |
| | isThisMonth | Checks if date is this month | date: DateInput | boolean |
| | isThisYear | Checks if date is this year | date: DateInput | boolean |
| | isPast | Checks if date is in the past | date: DateInput | boolean |
| | isFuture | Checks if date is in the future | date: DateInput | boolean |
| | isWeekend | Checks if date is weekend | date: DateInput | boolean |
| | isWeekday | Checks if date is weekday | date: DateInput | boolean |
| | isDayOfWeek | Checks if date is specific day | date: DateInput, day: number | boolean |
| | isMonday | Checks if date is Monday | date: DateInput | boolean |
| | isTuesday | Checks if date is Tuesday | date: DateInput | boolean |
| | isWednesday | Checks if date is Wednesday | date: DateInput | boolean |
| | isThursday | Checks if date is Thursday | date: DateInput | boolean |
| | isFriday | Checks if date is Friday | date: DateInput | boolean |
| | isSaturday | Checks if date is Saturday | date: DateInput | boolean |
| | isSunday | Checks if date is Sunday | date: DateInput | boolean |
| | getDayName | Gets day name | date: DateInput, format?: 'long' \| 'short' | string |
| | getDateRange | Gets date range | start: DateInput, end: DateInput | Date[] |
| | getDatesInMonth | Gets all dates in month | date: DateInput | Date[] |
| | getWeekdaysInRange | Gets weekdays in range | start: DateInput, end: DateInput | Date[] |
| | getWeekendsInRange | Gets weekends in range | start: DateInput, end: DateInput | Date[] |
| | getFirstDayOfMonth | Gets first day of month | date: DateInput | Date |
| | getLastDayOfMonth | Gets last day of month | date: DateInput | Date |
| | getFirstDayOfYear | Gets first day of year | date: DateInput | Date |
| | getLastDayOfYear | Gets last day of year | date: DateInput | Date |
| | getStartOfWeek | Gets start of week | date: DateInput | Date |
| | getEndOfWeek | Gets end of week | date: DateInput | Date |
| | getDaysDifference | Gets days between dates | date1: DateInput, date2: DateInput | number |
| Array Utilities |
| | chunk | Splits array into chunks | array: T[], size: number | T[][] |
| | shuffle | Randomly shuffles array | array: T[], mutate?: boolean | T[] |
| | findByKey | Finds item by key value | array: T[], key: string, value: any | T \| undefined |
| | groupBy | Groups array by key | array: T[], key: string | Record<string, T[]> |
| | pluck | Extracts values by key | array: T[], key: string | any[] |
| | unique | Removes duplicates | array: T[], key?: string | T[] |
| | sortBy | Sorts array by key | array: T[], key: string \| ((item: T) => any) | T[] |
| Object Utilities |
| | deepClone | Creates deep copy of object | obj: T | T |
| | pick | Picks properties from object | obj: T, keys: K[] | Pick<T, K> |
| | pickBy | Picks properties by predicate | obj: T, predicate: (value: any) => boolean | Partial<T> |
| | merge | Merges objects (shallow) | target: T, ...sources: Partial<T>[] | T |
| | mergeDeep | Merges objects (deep) | target: T, ...sources: any[] | T |
| | objectToArray | Converts object to array | obj: Record<string, any> | Array<{key: string, value: any}> |
| | objectToValues | Gets object values | obj: Record<string, any> | any[] |
| | objectToKeys | Gets object keys | obj: Record<string, any> | string[] |
| | objectToArrayBy | Converts object to array by key | obj: Record<string, any>, key: string | any[] |
| | arrayToObject | Converts array to object | array: any[], key: string | Record<string, any> |
| | objectToFormData | Converts object to FormData | obj: Record<string, any> | FormData |
| | formDataToObject | Converts FormData to object | formData: FormData | Record<string, any> |
| | isEmpty | Checks if value is empty | value: any | boolean |
| | hasNestedProperty | Checks for nested property | obj: object, path: string | boolean |
| | flattenObject | Flattens nested object | obj: object, prefix?: string | Record<string, any> |
| | omit | Omits properties from object | obj: T, keys: K[] | Omit<T, K> |
| Validation Utilities |
| | isEmail | Validates email address | email: string | boolean |
| | isURL | Validates URL | url: string | boolean |
| | isEven | Checks if number is even | num: number | boolean |
| | isOdd | Checks if number is odd | num: number | boolean |
TypeScript Support
This library is written in TypeScript and provides full type definitions out of the box. No additional @types packages are needed.
import { formatCurrency, FormatCurrencyOptions } from '@hubtel/utils';
const options: FormatCurrencyOptions = {
currency: 'USD',
locale: 'en-US',
minimumFractionDigits: 2
};
const formatted: string = formatCurrency(1234.56, options);Browser Support
- Chrome ≥ 60
- Firefox ≥ 60
- Safari ≥ 12
- Edge ≥ 79
Contributing
We welcome contributions! Please see our Contributing Guide for details.
License
MIT License - see LICENSE file for details.
Support
For support, please contact the Hubtel development team or open an issue on GitHub.
