utils-belt
v1.0.5
Published
A utility belt library with essential helper functions for JavaScript/TypeScript projects
Maintainers
Readme
Utils Belt
A utility belt library with essential helper functions for JavaScript/TypeScript projects.
Features
- 🚀 Micro-sized - Minimal bundle size with maximum utility
- 📦 Comprehensive - 100+ utility functions covering common use cases
- 🔒 Type Safe - Full TypeScript support with type definitions
- 🌐 Universal - Works in Node.js and browser environments
- 📚 Well Documented - JSDoc comments for all functions
- 🧪 Tested - Comprehensive test coverage
Installation
npm install utils-beltUsage
ES Modules
import {
range,
unique,
deepClone,
capitalize,
formatCurrency,
debounce
} from 'utils-belt';
// Array utilities
const numbers = range(1, 10); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const uniqueItems = unique([1, 2, 2, 3, 3, 4]); // [1, 2, 3, 4]
// Object utilities
const cloned = deepClone({ user: { name: 'John' } });
// String utilities
const title = capitalize('hello world'); // "Hello world"
// Number utilities
const price = formatCurrency(1234.56); // "$1,234.56"
// Function utilities
const debouncedSearch = debounce(searchFunction, 300);CommonJS
const {
range,
unique,
deepClone,
capitalize,
formatCurrency,
debounce
} = require('utils-belt');API Reference
Array Utilities
range(start, end, step?)- Creates an array of numbersunique(array)- Removes duplicate valuesgroupBy(array, keyFn)- Groups array elements by a keychunk(array, size)- Splits array into chunksflatten(array, depth?)- Flattens nested arraysshuffle(array)- Randomly shuffles arraysortBy(array, keyFn, order?)- Sorts array by key function
Object Utilities
deepClone(obj)- Creates a deep clone of an objectdeepMerge(...objects)- Merges multiple objects deeplypick(obj, keys)- Picks specified keys from an objectomit(obj, keys)- Omits specified keys from an objectget(obj, path, defaultValue?)- Gets nested property valueset(obj, path, value)- Sets nested property valuehas(obj, path)- Checks if object has nested property
String Utilities
capitalize(str)- Capitalizes first lettercamelCase(str)- Converts to camelCasekebabCase(str)- Converts to kebab-casesnakeCase(str)- Converts to snake_casepascalCase(str)- Converts to PascalCasetruncate(str, length, suffix?)- Truncates stringstripHtml(html)- Removes HTML tagsescapeHtml(str)- Escapes HTML characters
Number Utilities
clamp(value, min, max)- Clamps number between min/maxisBetween(value, min, max)- Checks if number is in rangeround(value, decimals?)- Rounds to decimal placesformatNumber(value, locale?)- Formats with separatorsformatCurrency(value, currency?, locale?)- Formats as currencyformatPercent(value, decimals?, locale?)- Formats as percentagerandomInt(min, max)- Generates random integerrandomFloat(min, max)- Generates random float
Function Utilities
debounce(func, delay)- Debounces function callsthrottle(func, delay)- Throttles function callsmemoize(func)- Memoizes function resultscompose(...fns)- Composes multiple functionspipe(...fns)- Pipes value through functionscurry(func, arity?)- Curries a functionpartial(func, ...args)- Partially applies argumentsonce(func)- Ensures function runs only once
Date Utilities
formatDate(date, format?)- Formats date to stringstartOfDay(date)- Gets start of dayendOfDay(date)- Gets end of dayaddDays(date, days)- Adds days to datesubDays(date, days)- Subtracts days from datedifferenceInDays(date1, date2)- Gets difference in daysisToday(date)- Checks if date is todaygetRelativeTime(date)- Gets relative time string
Validation Utilities
isDefined(value)- Checks if value is definedisString(value)- Checks if value is stringisNumber(value)- Checks if value is numberisObject(value)- Checks if value is objectisArray(value)- Checks if value is arrayisEmpty(value)- Checks if value is emptyisValidEmail(value)- Validates email formatisValidUrl(value)- Validates URL formatisValidCreditCard(value)- Validates credit card
Common Utilities
generateId()- Generates unique IDgenerateUuid()- Generates UUID v4sleep(ms)- Sleeps for millisecondsretryWithBackoff(fn, maxRetries?, baseDelay?)- Retries with backofftimeout(promise, ms)- Adds timeout to promisedeepFreeze(obj)- Deep freezes objectdeepCopy(obj)- Deep copies object
Examples
Working with Arrays
import { range, unique, groupBy, chunk } from 'utils-belt';
// Create a range of numbers
const numbers = range(1, 20, 2); // [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
// Remove duplicates
const uniqueNumbers = unique([1, 2, 2, 3, 3, 4]); // [1, 2, 3, 4]
// Group by category
const products = [
{ name: 'Apple', category: 'fruit' },
{ name: 'Banana', category: 'fruit' },
{ name: 'Carrot', category: 'vegetable' }
];
const grouped = groupBy(products, p => p.category);
// { fruit: [...], vegetable: [...] }
// Split into chunks
const chunks = chunk([1, 2, 3, 4, 5, 6], 2); // [[1, 2], [3, 4], [5, 6]]Working with Objects
import { deepClone, pick, omit, get, set } from 'utils-belt';
// Deep clone
const original = { user: { name: 'John', settings: { theme: 'dark' } } };
const cloned = deepClone(original);
// Pick specific keys
const userInfo = pick(original.user, ['name']); // { name: 'John' }
// Omit specific keys
const userWithoutName = omit(original.user, ['name']); // { settings: { theme: 'dark' } }
// Get nested property
const theme = get(original, 'user.settings.theme'); // 'dark'
// Set nested property
set(original, 'user.settings.theme', 'light');Working with Strings
import {
capitalize,
camelCase,
kebabCase,
truncate,
stripHtml
} from 'utils-belt';
// Case conversions
capitalize('hello world'); // "Hello world"
camelCase('hello world'); // "helloWorld"
kebabCase('helloWorld'); // "hello-world"
snakeCase('helloWorld'); // "hello_world"
// String manipulation
truncate('This is a very long string', 20); // "This is a very long..."
stripHtml('<p>Hello <strong>World</strong></p>'); // "Hello World"Working with Functions
import { debounce, throttle, memoize, compose } from 'utils-belt';
// Debounce search input
const debouncedSearch = debounce((query) => {
// Perform search
console.log('Searching for:', query);
}, 300);
// Throttle scroll events
const throttledScroll = throttle(() => {
// Handle scroll
console.log('Scroll event');
}, 100);
// Memoize expensive calculation
const memoizedFactorial = memoize((n) => {
if (n <= 1) return 1;
return n * memoizedFactorial(n - 1);
});
// Compose functions
const processText = compose(
(text) => text.trim(),
(text) => text.toLowerCase(),
(text) => text.replace(/\s+/g, '-')
);
const result = processText(' Hello World '); // "hello-world"Working with Dates
import {
formatDate,
addDays,
isToday,
getRelativeTime
} from 'utils-belt';
// Format dates
const date = new Date();
formatDate(date, 'YYYY-MM-DD HH:mm'); // "2024-01-15 14:30"
// Date arithmetic
const tomorrow = addDays(date, 1);
const nextWeek = addDays(date, 7);
// Date checks
isToday(date); // true/false
// Relative time
getRelativeTime(date); // "2 hours ago"Working with Validation
import {
isDefined,
isValidEmail,
isValidUrl,
validateSchema
} from 'utils-belt';
// Type checks
isDefined('hello'); // true
isDefined(null); // false
// Format validation
isValidEmail('[email protected]'); // true
isValidUrl('https://example.com'); // true
// Schema validation
const userSchema = {
name: (value: any) => typeof value === 'string' && value.length > 0,
email: isValidEmail,
age: (value: any) => typeof value === 'number' && value >= 0
};
const user = { name: 'John', email: '[email protected]', age: 30 };
const validation = validateSchema(user, userSchema);
// { isValid: true, errors: [] }Browser Support
- Chrome 60+
- Firefox 55+
- Safari 12+
- Edge 79+
Node.js Support
- Node.js 14+
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Run tests:
npm test - Submit a pull request
License
MIT License - see LICENSE file for details.
Changelog
1.0.0
- Initial release
- 100+ utility functions
- Full TypeScript support
- Comprehensive documentation
- Browser and Node.js support
