universal-helper-functions
v1.0.2
Published
A lightweight, comprehensive utility library for JavaScript/TypeScript projects - type checks, string manipulation, array utilities, and more. Framework-agnostic and works with any library or framework.
Maintainers
Readme
universal-helper-functions - Utility Helpers Library
A lightweight, zero-dependency utility library providing a comprehensive collection of helper functions, type checks, string manipulation utilities, and more for JavaScript/TypeScript projects. Framework-agnostic - works with any framework, library, or vanilla JavaScript.
📦 Installation
npm install universal-helper-functions
# or
yarn add universal-helper-functions
# or
pnpm add universal-helper-functions🎯 Features
1. Type Checks (35 Functions)
Robust type checking utilities for common JavaScript types and patterns.
Available Checks
isBool(value)- Check if value is a booleanisTrue(value)- Check if value represents true (true,'true','1','yes','on')isFalse(value)- Check if value represents false (false,'false','0','no','off',null,undefined)isBooleanLike(value)- Check if value can be interpreted as a booleantoBoolean(value, fallback?)- Convert boolean-like input to boolean with optional fallbackisNegative(value)- Check if number is negativeisPositive(value)- Check if number is positiveisZero(value)- Check if value equals zeroisNumber(value)- Check if value is a numberisString(value)- Check if value is a stringisArray(value)- Check if value is an arrayisObject(value)- Check if value is a plain objectisNull(value)- Check if value is nullisUndefined(value)- Check if value is undefinedisNullOrUndefined(value)- Check if value is null or undefinedisFunction(value)- Check if value is a functionisDate(value)- Check if value is a Date objectisRegex(value)- Check if value is a RegExpisPromise(value)- Check if value is a PromiseisIterable(value)- Check if value is iterableisEmpty(value)- Check if value is empty (string, array, object, null, undefined)isFalsy(value)- Check if value is falsyisTruthy(value)- Check if value is truthyisEmail(value)- Check if string is valid email formatisUrl(value)- Check if string is valid URL formatisPhoneNumber(value)- Check if string matches phone number patternisIpAddress(value)- Check if string is valid IP address (IPv4 or IPv6)isPalindrome(value)- Check if string is a palindromeisAlphanumeric(value)- Check if string contains only alphanumeric charactersisNumeric(value)- Check if value can be converted to a numberisInteger(value)- Check if value is an integerisFloat(value)- Check if value is a floating-point numberisEven(value)- Check if number is evenisOdd(value)- Check if number is oddisPrime(value)- Check if number is prime
Usage Example:
import { isBool, isTrue, isFalse, toBoolean, isNegative, isEmpty } from 'universal-helper-functions';
isBool(true); // true
isTrue('true'); // true
isTrue(true); // true
isTrue(undefined); // false
isFalse('false'); // true
isFalse(null); // true
toBoolean('yes'); // true
toBoolean('no'); // false
toBoolean('random', true); // true (fallback)
isNegative(-5); // true
isEmpty(''); // true
isEmpty([]); // true
isEmail('[email protected]'); // true2. String Casing & Manipulation (30 Functions)
Convert strings between different casing styles and manipulate text.
Available Methods
toCamelCase(string)- Convert to camelCasetoSnakeCase(string)- Convert to snake_casetoKebabCase(string)- Convert to kebab-casetoPascalCase(string)- Convert to PascalCasetoTitleCase(string)- Convert to Title CasetoConstantCase(string)- Convert to CONSTANT_CASEtoFlatCase(string)- Convert to flatcasetoPathCase(string)- Convert to path/casetoDotCase(string)- Convert to dot.casetoSentenceCase(string)- Convert to Sentence casecapitalize(string)- Capitalize first letterdecapitalize(string)- Remove capitalization from first letterreverse(string)- Reverse string charactersrepeat(string, count)- Repeat string n timestruncate(string, length, suffix)- Truncate string with ellipsispadStart(string, length, pad)- Pad string from startpadEnd(string, length, pad)- Pad string from endtrim(string)- Remove leading/trailing whitespace (works like native trim)trimStart(string)- Remove leading whitespacetrimEnd(string)- Remove trailing whitespaceslugify(string)- Convert to URL-friendly slugremoveVowels(string)- Remove all vowels from stringremoveConsonants(string)- Remove all consonants from stringremoveWhitespace(string)- Remove all whitespaceremoveSpecialChars(string)- Remove special characterstoCharArray(string)- Convert string to character arraywordCount(string)- Count words in stringcharCount(string)- Count unique charactersreplaceLast(string, search, replace)- Replace last occurrencetemplate(template, data)- Simple template string replacement
Usage Example:
import { toCamelCase, toSnakeCase, capitalize } from 'universal-helper-functions';
toCamelCase('hello-world-example'); // 'helloWorldExample'
toSnakeCase('helloWorldExample'); // 'hello_world_example'
toPascalCase('hello_world'); // 'HelloWorld'
toTitleCase('hello world'); // 'Hello World'
capitalize('hello'); // 'Hello'
slugify('Hello World Example'); // 'hello-world-example'
truncate('This is a long string', 10); // 'This is...'3. Array Utilities (27 Functions)
Helper functions for array manipulation and transformation.
Available Methods
chunk(array, size)- Split array into chunkscompact(array)- Remove falsy valuesflatten(array, depth)- Flatten nested arraysunique(array)- Get unique valuesuniqueBy(array, key)- Get unique values by propertydifference(array1, array2)- Find differences between arraysintersection(array1, array2)- Find common elementsunion(array1, array2)- Combine unique elementsshuffle(array)- Randomly shuffle arrayreverse(array)- Reverse array (non-mutating)first(array)- Get first elementlast(array)- Get last elementnth(array, index)- Get element at indexremove(array, value)- Remove specific valueremoveAt(array, index)- Remove element at indexrotate(array, steps)- Rotate array elementssum(array)- Sum all numbers in arrayaverage(array)- Get average of numbersmax(array)- Get maximum valuemin(array)- Get minimum valuegroupBy(array, key)- Group array by propertysortBy(array, key, order)- Sort array by propertyfilter(array, predicate)- Filter arraymap(array, callback)- Map arrayreduce(array, callback, initial)- Reduce arrayfill(array, value, start, end)- Fill array with valueincludes(array, value)- Check if array includes value
Usage Example:
import { chunk, flatten, unique, shuffle } from 'universal-helper-functions';
chunk([1,2,3,4,5], 2); // [[1,2], [3,4], [5]]
flatten([1, [2, [3, 4]]], 2); // [1, 2, 3, 4]
unique([1,2,2,3,3,3]); // [1, 2, 3]
shuffle([1,2,3,4,5]); // [3,1,4,5,2]4. Object Utilities (25 Functions)
Helper functions for object manipulation and transformation.
Available Methods
keys(object)- Get object keysvalues(object)- Get object valuesentries(object)- Get object entriespick(object, keys)- Pick specific propertiesomit(object, keys)- Omit specific propertiesmerge(target, source)- Shallow merge objectsdeepMerge(target, source)- Deep merge objectsclone(object)- Shallow clone objectdeepClone(object)- Deep clone objecthasProperty(object, key)- Check if property existshasOwnProperty(object, key)- Check own propertyisEmpty(object)- Check if object is emptysize(object)- Get number of propertiesinvert(object)- Invert keys and valuesmapKeys(object, fn)- Transform all keysmapValues(object, fn)- Transform all valuesfilterKeys(object, predicate)- Filter by key namesfilterValues(object, predicate)- Filter by valuesdefaults(object, defaultObj)- Set default valuesfindKey(object, predicate)- Find key by conditionfindValue(object, predicate)- Find value by conditiontoQueryString(object)- Convert to URL query stringfromQueryString(string)- Parse query string to objectgetPath(object, path)- Get nested value by path (lodash style)setPath(object, path, value)- Set nested value by path
Usage Example:
import { pick, omit, merge, deepClone } from 'universal-helper-functions';
const user = { id: 1, name: 'John', email: '[email protected]', password: '123' };
pick(user, ['id', 'name']); // { id: 1, name: 'John' }
omit(user, ['password']); // { id: 1, name: 'John', email: '[email protected]' }
merge({ a: 1 }, { b: 2 }); // { a: 1, b: 2 }
deepClone(nestedObject); // Complete deep copy5. Math Utilities (24 Functions)
Scientific and mathematical helper functions.
Available Methods
round(number, decimals)- Round to decimal placesfloor(number)- Floor numberceil(number)- Ceiling numberabs(number)- Absolute valuesqrt(number)- Square rootpow(base, exponent)- Power functionmin(...numbers)- Find minimummax(...numbers)- Find maximumclamp(value, min, max)- Clamp value between min/maxrandom(min, max)- Random number in rangerandomInt(min, max)- Random integerpercentage(value, total)- Calculate percentagefactorial(number)- Calculate factorialfibonacci(n)- Get fibonacci numberdistance(x1, y1, x2, y2)- Calculate distance between pointsaverage(...numbers)- Calculate averagesum(...numbers)- Sum numbersmedian(array)- Get median valuemode(array)- Get mode (most common value)standardDeviation(array)- Calculate standard deviationvariance(array)- Calculate variancegcd(a, b)- Greatest common divisorlcm(a, b)- Least common multipleisEven(number)- Check if evenisOdd(number)- Check if oddisDivisibleBy(number, divisor)- Check divisibility
Usage Example:
import { round, clamp, random, percentage } from 'universal-helper-functions';
round(3.14159, 2); // 3.14
clamp(150, 0, 100); // 100
random(1, 10); // Random number between 1-10
percentage(25, 100); // 25
factorial(5); // 1206. Date & Time Utilities (27 Functions)
Work with dates and time intervals easily.
Available Methods
now()- Get current timestamptoday()- Get today's dateyesterday()- Get yesterday's datetomorrow()- Get tomorrow's dateaddDays(date, days)- Add days to datesubtractDays(date, days)- Subtract days from dateaddMonths(date, months)- Add months to dateaddYears(date, years)- Add years to datestartOfDay(date)- Get start of dayendOfDay(date)- Get end of daystartOfMonth(date)- Get start of monthendOfMonth(date)- Get end of monthstartOfYear(date)- Get start of yearendOfYear(date)- Get end of yearformat(date, format)- Format date as stringparse(dateString, format)- Parse date stringdifference(date1, date2, unit)- Get difference between datesisSameDay(date1, date2)- Check if same dayisBefore(date1, date2)- Check if beforeisAfter(date1, date2)- Check if afterisBetween(date, start, end)- Check if between datesisToday(date)- Check if todayisLeapYear(year)- Check if leap yeardaysInMonth(year, month)- Get days in monthweekOfYear(date)- Get week number of yeardayOfYear(date)- Get day number of yeargetAge(birthDate)- Calculate age from birth date
Usage Example:
import { addDays, format, difference } from 'universal-helper-functions';
addDays(new Date(), 7); // Date 7 days from now
format(new Date(), 'yyyy-MM-dd'); // '2024-03-27'
difference(new Date('2024-01-01'), new Date(), 'days'); // Days elapsed
getAge('1990-05-15'); // Age in years7. Promise & Async Utilities (11 Functions)
Helpers for working with promises and asynchronous code.
Available Methods
delay(ms)- Create a promise that resolves after delaytimeout(promise, ms)- Reject promise after timeoutretry(fn, options)- Retry promise with exponential backoffrace(promises)- Race multiple promisesall(promises)- Wait for all promisesallSettled(promises)- Wait for all promises (settled)any(promises)- Return first fulfilled promisewaterfall(tasks, initial)- Execute tasks in sequenceparallel(tasks, limit)- Execute tasks in parallel with limitmemoize(fn)- Memoize async function resultsdebounce(fn, delay)- Debounce function callsthrottle(fn, delay)- Throttle function callsonce(fn)- Execute function only oncecache(fn, ttl)- Cache function results with TTL
Usage Example:
import { delay, retry, debounce } from 'universal-helper-functions';
await delay(1000); // Wait 1 second
await retry(apiCall, { attempts: 3, backoff: 'exponential' });
const debouncedSearch = debounce(search, 300);8. Validation Utilities (20 Functions)
Input validation helpers for common data types.
Available Methods
isStrongPassword(password)- Validate strong passwordisWeakPassword(password)- Check if password is weakisCreditCard(number)- Validate credit card numberisPostalCode(code, country)- Validate postal code formatisCurrency(value)- Validate currency formatisHexColor(value)- Validate hex colorisRgbColor(value)- Validate RGB colorisUsername(username)- Validate username formatisSlug(slug)- Validate URL slugisUuid(uuid)- Validate UUID formatisMd5(hash)- Validate MD5 hashisSha1(hash)- Validate SHA1 hashisSha256(hash)- Validate SHA256 hashisJSON(string)- Validate JSON stringisBase64(string)- Validate Base64 stringisUrl(url, options)- Validate URL with optionsisIpAddress(ip)- Validate IP addressisPort(port)- Validate port numberisMimeType(type)- Validate MIME typeisDateString(string, format)- Validate date string
Usage Example:
import { isStrongPassword, isEmail, isCreditCard } from 'universal-helper-functions';
isStrongPassword('P@ssw0rd123!'); // true
isEmail('[email protected]'); // true
isCreditCard('4532111111111111'); // true9. Color & Format Utilities (23 Functions)
Work with colors and format different data types.
Available Methods
Color Utilities:
hexToRgb(hex)- Convert hex to RGBrgbToHex(r, g, b)- Convert RGB to hexhexToHsl(hex)- Convert hex to HSLhslToHex(h, s, l)- Convert HSL to hexlighten(color, amount)- Lighten colordarken(color, amount)- Darken colorsaturate(color, amount)- Increase saturationdesaturate(color, amount)- Decrease saturationrotate(color, degrees)- Rotate huecomplement(color)- Get complementary colorfindSimilarColor(color, array)- Find closest color match
Format Utilities:
formatBytes(bytes)- Format bytes to human readableformatNumber(number, options)- Format number with separatorsformatCurrency(amount, currency)- Format as currencyformatPercent(value, decimals)- Format as percentageformatDuration(ms)- Format milliseconds to readableformatTime(seconds)- Format seconds to HH:MM:SSformatPhone(phone, format)- Format phone numberformatSSN(ssn)- Format social security numberformatCreditCard(card)- Format credit card numberformatJson(obj, space)- Format JSON with indentation
Usage Example:
import { hexToRgb, formatBytes, formatCurrency } from 'universal-helper-functions';
hexToRgb('#ff0000'); // { r: 255, g: 0, b: 0 }
formatBytes(1024 * 1024); // '1 MB'
formatCurrency(1234.56, 'USD'); // '$1,234.56'
formatPhone('1234567890', 'US'); // '(123) 456-7890'10. Encoding & Encryption Utilities (12 Functions)
Encode, decode, and simple encryption operations.
Available Methods
toBase64(string)- Encode to Base64fromBase64(base64)- Decode from Base64toUrlEncoded(string)- URL encodefromUrlEncoded(string)- URL decodetoHex(string)- Convert to hexadecimalfromHex(hex)- Convert from hexadecimaltoMorse(string)- Convert to Morse codefromMorse(morse)- Convert from Morse codecaesarCipher(string, shift)- Simple Caesar cipher encodingmd5(string)- Generate MD5 hashsha1(string)- Generate SHA1 hashsha256(string)- Generate SHA256 hash
Usage Example:
import { toBase64, fromBase64, toHex } from 'universal-helper-functions';
toBase64('hello'); // 'aGVsbG8='
fromBase64('aGVsbG8='); // 'hello'
toHex('hello'); // '68656c6c6f'11. Browser/DOM Utilities (29 Functions)
Utilities designed for browser and DOM manipulation in any JavaScript environment.
Available Methods
getQueryParam(name)- Get URL query parametergetQueryParams()- Get all query parameterssetQueryParam(name, value)- Set URL query parameterremoveQueryParam(name)- Remove query parametergetHash()- Get URL hash/fragmentsetHash(hash)- Set URL hashgetHostname()- Get current hostnamegetPathname()- Get current pathnamegetOrigin()- Get origin URLredirect(url)- Redirect to URLreloadPage()- Reload current pagegoBack()- Go back in historygoForward()- Go forward in historyisLocalHost()- Check if running on localhostisDevelopment()- Check if in developmentgetScreenSize()- Get viewport dimensionsgetScrollPosition()- Get current scroll positionscrollToTop()- Scroll to topscrollToElement(selector)- Scroll to elementgetClipboard()- Get clipboard contentsetClipboard(text)- Copy text to clipboardisOnline()- Check internet connectivityaddEventListener(target, event, handler)- Add event listenerremoveEventListener(target, event, handler)- Remove event listenerstopPropagation(event)- Stop event propagationpreventDefault(event)- Prevent default actiongetLocalStorage(key)- Get from localStoragesetLocalStorage(key, value)- Set in localStorageremoveLocalStorage(key)- Remove from localStoragegetSessionStorage(key)- Get from sessionStoragesetSessionStorage(key, value)- Set in sessionStorage
Usage Example:
import { getQueryParam, setClipboard, getScreenSize } from 'universal-helper-functions';
getQueryParam('id'); // Get 'id' from URL params
setClipboard('copied text'); // Copy to clipboard
getScreenSize(); // { width: 1920, height: 1080 }12. Express/Server Utilities (18 Functions)
Utilities specifically designed for Express applications.
Available Methods
parseJsonBody(body)- Safely parse JSON bodygetClientIp(req)- Extract client IP addresssetResponseHeaders(res, headers)- Set multiple response headerssendError(res, statusCode, message)- Send error responsesendSuccess(res, data, statusCode)- Send success responseisJsonRequest(req)- Check if request is JSONgetContentType(req)- Get request content typegenerateRequestId()- Generate unique request IDcreateErrorResponse(error)- Format error for responsecreateSuccessResponse(data)- Format data for responsevalidateRequired(data, fields)- Validate required fieldssanitizeData(data)- Remove sensitive fieldsgetCookie(req, name)- Get cookie valuesetCookie(res, name, value, options)- Set cookieremoveCookie(res, name)- Remove cookiegetAuthHeader(req)- Get authorization headerextractBearerToken(req)- Extract Bearer tokenrateLimit(req, options)- Simple rate limiting
Usage Example:
import { sendSuccess, sendError, getClientIp } from 'universal-helper-functions';
// In Express route handler
app.get('/api/users/:id', (req, res) => {
const clientIp = getClientIp(req);
try {
sendSuccess(res, { id: 1, name: 'John' });
} catch (error) {
sendError(res, 500, 'Internal server error');
}
});13. File & Path Utilities (16 Functions)
Work with file paths and file operations.
Available Methods
basename(path)- Get filename from pathdirname(path)- Get directory from pathextname(path)- Get file extensionjoin(...paths)- Join path segmentsresolve(...paths)- Resolve absolute pathnormalize(path)- Normalize pathrelative(from, to)- Get relative pathisAbsolute(path)- Check if path is absolutegetFileMimeType(filename)- Get MIME typegetFileExtension(filename)- Get file extensionisValidPath(path)- Validate path formatfileExists(path)- Check if file exists (Node.js)readFile(path)- Read file contents (Node.js)writeFile(path, data)- Write to file (Node.js)deleteFile(path)- Delete file (Node.js)getFileSize(path)- Get file size (Node.js)
Usage Example:
import { basename, dirname, extname } from 'universal-helper-functions';
basename('/home/user/file.txt'); // 'file.txt'
dirname('/home/user/file.txt'); // '/home/user'
extname('file.txt'); // '.txt'14. Environment Utilities (10 Functions)
Work with environment variables and environment detection.
Available Methods
getEnv(key, defaultValue)- Get environment variableisDevelopment()- Check if development modeisProduction()- Check if production modeisTesting()- Check if testing modegetNodeVersion()- Get Node.js versiongetPlatform()- Get OS platformgetArch()- Get CPU architecturegetCwd()- Get current working directorygetEnvPath()- Get path to .env fileloadEnv(path)- Load environment from file
Usage Example:
import { isDevelopment, getEnv } from 'universal-helper-functions';
const apiUrl = isDevelopment() ? 'http://localhost:3000' : getEnv('API_URL');📚 Full Usage Examples
Express.js API Example
import express from 'express';
import {
sendSuccess,
sendError,
validateRequired,
getClientIp,
generateRequestId
} from 'universal-helper-functions';
const app = express();
app.use(express.json());
app.post('/api/users', (req, res) => {
const requestId = generateRequestId();
const clientIp = getClientIp(req);
// Validate required fields
const validation = validateRequired(req.body, ['name', 'email']);
if (!validation.isValid) {
return sendError(res, 400, validation.errors.join(', '));
}
try {
const user = { id: 1, ...req.body };
sendSuccess(res, user);
} catch (error) {
console.error(`[${requestId}] Error from ${clientIp}:`, error);
sendError(res, 500, 'Internal server error');
}
});🚀 Quick Start
// Import individual utilities
import { toCamelCase, chunk, isEmail } from 'universal-helper-functions';
// Or use namespaces
import { String, Array, Validation } from 'universal-helper-functions';
String.toCamelCase('hello-world'); // 'helloWorld'
Array.chunk([1,2,3,4], 2); // [[1,2], [3,4]]
Validation.isEmail('[email protected]'); // true📖 API Documentation
See API.md for detailed API documentation and type definitions.
💡 Features Highlights
✅ Zero Dependencies - No external packages required
✅ TypeScript Support - Full type definitions included
✅ Tree-Shakeable - Import only what you need
✅ Lightweight - Minimal bundle size
✅ Well-Tested - Comprehensive test coverage
✅ Browser & Node.js - Works in all environments
✅ ESM & CommonJS - Multiple module formats
✅ Chainable - Many utilities support method chaining
✅ Extensible - Easy to add custom utilities
📦 Browser Support
- Chrome (latest)
- Firefox (latest)
- Safari (latest)
- Edge (latest)
- Node.js 14+
📄 License
MIT - Copyright (c) 2024 Nitesh Upadhayay
🤝 Contributing
Contributions are welcome! Please see CONTRIBUTING.md for guidelines.
📞 Support & Contact
For issues, questions, or suggestions, please:
- Open an issue on GitHub
- Email: [email protected]
- GitHub: @NiteshCodes
Author: Nitesh Upadhayay
