@chhanganisab/all-helper-functions
v1.0.6
Published
A collection of 100+ utility functions
Downloads
13
Readme
All Helper Functions
A comprehensive TypeScript utility library with 50+ reusable helper functions for common development tasks. This package provides validation, string manipulation, array operations, object utilities, number utilities, date formatting, and general utility functions.
🚀 Features
- TypeScript Support: Full TypeScript support with type definitions
- Zero Dependencies: Lightweight with no external dependencies
- Tree Shakeable: Import only what you need
- Well Tested: Reliable and production-ready functions
- MIT License: Free to use in any project
📦 Installation
npm install @chhanganisab/all-helper-functionsyarn add @chhanganisab/all-helper-functionspnpm add @chhanganisab/all-helper-functions🔧 Usage
Import individual functions
import { isValidEmail, capitalize, unique, debounce } from '@chhanganisab/all-helper-functions';
// Validate email
const isValid = isValidEmail('[email protected]'); // true
// Capitalize string
const capitalized = capitalize('hello world'); // 'Hello world'
// Remove duplicates from array
const uniqueArray = unique([1, 2, 2, 3, 3, 4]); // [1, 2, 3, 4]
// Debounce function
const debouncedSearch = debounce((query: string) => {
// Search logic here
}, 300);Import all functions
import * as Utils from '@chhanganisab/all-helper-functions';
const isValid = Utils.isValidEmail('[email protected]');
const formatted = Utils.formatDate(new Date(), 'YYYY-MM-DD');📚 API Reference
🔍 Validators
Email & Communication
isValidEmail(email: string): boolean- Validates email formatisValidPhoneNumber(phone: string): boolean- Validates phone number formatisValidUsername(username: string): boolean- Validates username format
Data Validation
isNumeric(value: string): boolean- Checks if string contains only numbersisAlpha(value: string): boolean- Checks if string contains only lettersisAlphanumeric(value: string): boolean- Checks if string contains only letters and numbersisAlphaNumericWithSpaces(value: string): boolean- Checks if string contains letters, numbers, and spacesisLowerCase(value: string): boolean- Checks if string is all lowercaseisUpperCase(value: string): boolean- Checks if string is all uppercase
Security & Authentication
isStrongPassword(password: string): boolean- Validates password strengthisBase64(value: string): boolean- Checks if string is valid Base64isAscii(value: string): boolean- Checks if string contains only ASCII characters
Data Formats
isJSON(value: string): boolean- Validates JSON string formatisUUID(value: string): boolean- Validates UUID formatisHexColor(value: string): boolean- Validates hex color formatisCreditCard(value: string): boolean- Validates credit card number formatisIPAddress(value: string): boolean- Validates IP address formatisValidPostalCode(postalCode: string): boolean- Validates postal code formatisValidSlug(slug: string): boolean- Validates URL slug format
Content Validation
isEmptyString(value: string): boolean- Checks if string is empty or whitespaceisValidDate(value: string | Date): boolean- Validates date formatisEmoji(value: string): boolean- Checks if string contains emoji characters
🔤 String Utilities
capitalize(str: string): string- Capitalizes the first letter of a stringcamelCase(str: string): string- Converts string to camelCase formatkebabCase(str: string): string- Converts string to kebab-case formatsnakeCase(str: string): string- Converts string to snake_case formatpascalCase(str: string): string- Converts string to PascalCase formattruncate(str: string, length: number, suffix?: string): string- Truncates string to specified lengthreverse(str: string): string- Reverses a stringdebounce<T>(func: T, wait: number): T- Creates a debounced functionthrottle<T>(func: T, limit: number): T- Creates a throttled function
🔢 Number Utilities
clamp(value: number, min: number, max: number): number- Clamps a number between min and max valuessum(...numbers: number[]): number- Calculates the sum of numbersrandom(min: number, max: number): number- Generates a random number between min and maxround(num: number, decimals?: number): number- Rounds a number to specified decimal placesformatNumber(num: number, locale?: string): string- Formats a number with locale
📅 Date Utilities
formatDate(date: Date, format: string): string- Formats date according to specified formataddDays(date: Date, days: number): Date- Adds specified number of days to a dateisToday(date: Date): boolean- Checks if date is todaydaysBetween(date1: Date, date2: Date): number- Calculates days between two dates
📋 Array Utilities
unique<T>(arr: T[]): T[]- Removes duplicate values from arraychunk<T>(arr: T[], size: number): T[][]- Splits array into chunks of specified sizeflatten<T>(arr: (T | T[])[]): T[]- Flattens nested arraysshuffle<T>(arr: T[]): T[]- Shuffles array elements randomlygroupBy<T, K>(arr: T[], key: keyof T | ((item: T) => K)): Record<K, T[]>- Groups array by keyintersection<T>(arr1: T[], arr2: T[]): T[]- Returns common elements between arraysdifference<T>(arr1: T[], arr2: T[]): T[]- Returns elements in arr1 but not in arr2
📦 Object Utilities
isEmpty(obj: any): boolean- Checks if object is emptydeepClone<T>(obj: T): T- Creates a deep clone of an objectpick<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K>- Picks specified keys from objectomit<T, K extends keyof T>(obj: T, keys: K[]): Omit<T, K>- Omits specified keys from objectmerge<T, U>(target: T, source: U): T & U- Deep merges two objects
🛠️ General Utilities
memoize<T>(func: T): T- Creates a memoized version of a functionretry<T>(fn: () => Promise<T>, maxAttempts?: number, delay?: number): Promise<T>- Retries async functionsleep(ms: number): Promise<void>- Creates a delay for specified milliseconds
💡 Examples
Form Validation
import {
isValidEmail,
isStrongPassword,
isValidPhoneNumber
} from '@chhanganisab/all-helper-functions';
const validateForm = (formData: any) => {
const errors = [];
if (!isValidEmail(formData.email)) {
errors.push('Invalid email address');
}
if (!isStrongPassword(formData.password)) {
errors.push('Password is not strong enough');
}
if (!isValidPhoneNumber(formData.phone)) {
errors.push('Invalid phone number');
}
return errors;
};Data Processing
import {
unique,
chunk,
capitalize,
formatDate,
groupBy,
shuffle
} from '@chhanganisab/all-helper-functions';
// Process user data
const users = [
{ name: 'john doe', email: '[email protected]', role: 'admin' },
{ name: 'jane smith', email: '[email protected]', role: 'user' },
{ name: 'john doe', email: '[email protected]', role: 'admin' } // duplicate
];
// Remove duplicates and format names
const processedUsers = unique(users.map(user => user.email))
.map(email => users.find(u => u.email === email))
.map(user => ({
...user,
name: capitalize(user.name)
}));
// Group by role
const usersByRole = groupBy(processedUsers, 'role');
// Shuffle for random order
const shuffledUsers = shuffle(processedUsers);
// Split into chunks for pagination
const userChunks = chunk(processedUsers, 10);
// Format current date
const today = formatDate(new Date(), 'YYYY-MM-DD');Object Manipulation
import {
isEmpty,
deepClone,
pick,
omit,
merge
} from '@chhanganisab/all-helper-functions';
const originalObject = {
user: {
name: 'John',
email: '[email protected]',
preferences: {
theme: 'dark',
notifications: true
}
},
settings: {},
metadata: {
createdAt: new Date(),
version: '1.0.0'
}
};
// Check if settings object is empty
if (isEmpty(originalObject.settings)) {
console.log('Settings object is empty');
}
// Pick only user data
const userData = pick(originalObject, ['user']);
// Omit sensitive data
const publicData = omit(originalObject, ['metadata']);
// Create a deep clone for safe modification
const clonedObject = deepClone(originalObject);
clonedObject.user.preferences.theme = 'light';
// Merge with new settings
const updatedObject = merge(originalObject, {
user: { preferences: { theme: 'light' } },
settings: { debug: true }
});Performance Optimization
import {
debounce,
throttle,
memoize,
retry,
sleep
} from '@chhanganisab/all-helper-functions';
// Debounced search
const debouncedSearch = debounce((query: string) => {
console.log('Searching for:', query);
// API call here
}, 300);
// Throttled scroll handler
const throttledScroll = throttle(() => {
console.log('Scroll position:', window.scrollY);
}, 100);
// Memoized expensive calculation
const expensiveCalculation = memoize((n: number) => {
console.log('Calculating...');
return n * n * n;
});
// Retry API call
const fetchData = async () => {
return await retry(
async () => {
const response = await fetch('/api/data');
if (!response.ok) throw new Error('API failed');
return response.json();
},
3, // max attempts
1000 // delay between attempts
);
};
// Sleep utility
const delayedAction = async () => {
console.log('Starting...');
await sleep(2000); // wait 2 seconds
console.log('Finished!');
};String Manipulation
import {
capitalize,
camelCase,
kebabCase,
snakeCase,
pascalCase,
truncate,
reverse
} from '@chhanganisab/all-helper-functions';
const text = 'hello world example';
console.log(capitalize(text)); // 'Hello world example'
console.log(camelCase(text)); // 'helloWorldExample'
console.log(kebabCase(text)); // 'hello-world-example'
console.log(snakeCase(text)); // 'hello_world_example'
console.log(pascalCase(text)); // 'HelloWorldExample'
console.log(truncate(text, 10)); // 'hello wo...'
console.log(reverse(text)); // 'elpmaxe dlrow olleh'🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
👨💻 Author
Chhanganisab - LinkedIn
⭐ Support
If you find this library helpful, please consider giving it a star on GitHub!
Made with ❤️ for the developer community
