UtilityHelpers Documentation
A comprehensive collection of utility functions designed to simplify common tasks in JavaScript development. Includes robust methods for image processing, array manipulation, string operations, and more.
Image Utilities
getImageDetails(imageSrc, calculateAverageColor)
Fetches basic image details like width, height, size, and format. Optionally calculates average color.
UtilityHelpers.getImageDetails('https://example.com/image.jpg', true).then(details => {
console.log(details);
// Output:
// {
// width: 800,
// height: 600,
// aspectRatio: 1.33,
// format: 'jpeg',
// size: 10240,
// averageColor: { r: 255, g: 255, b: 255 }
// }
});
getImageOrientation(image)
Determines image orientation: landscape, portrait, or square.
const orientation = UtilityHelpers.getImageOrientation(imgElement);
// Output: 'landscape'
formatBytes(bytes, decimals)
Formats bytes into human-readable format (e.g., KB, MB).
const size = UtilityHelpers.formatBytes(1500000);
// Output: '1.43 MB'
getImageFormat(mimeType)
Returns user-friendly format name from MIME type.
const format = UtilityHelpers.getImageFormat('image/svg+xml');
// Output: 'SVG'
getAverageImageColor(imageSrc)
Calculates average color of an image.
UtilityHelpers.getAverageImageColor('https://example.com/image.jpg').then(color => {
console.log(color);
// Output: { r: 100, g: 150, b: 200 }
});
getImageBase64(imageSrc, options)
Converts image to Base64 string with optional format and quality.
UtilityHelpers.getImageBase64('image.jpg').then(base64 => {
// Output: 'data:image/jpeg;base64,/9j/4AAQSkZJRg...'
});
getLuminance(color)
Calculates luminance of a color for contrast checks.
const luminance = UtilityHelpers.getLuminance('rgb(255, 255, 255)');
// Output: 1 (white is brightest)
getContrastRatio(color1, color2)
Calculates contrast ratio between two lines.
const ratio = UtilityHelpers.getContrastRatio('rgb(0, 0, 0)', 'rgb(255, 255, 255)');
// Output: 21 (maximum contrast)
Array Utilities
chunk(array, size)
Splits array into chunks of specific size.
const chunks = UtilityHelpers.chunk([1, 2, 3, 4], 2);
// Output: [[1, 2], [3, 4]]
groupBy(array, key)
Groups array items by key or function.
const grouped = UtilityHelpers.groupBy(users, 'role');
// Output: { admin: [{ id: 1, ... }], user: [{ id: 2, ... }] }
shuffleArray(array)
Randomly shuffles array elements.
const shuffled = UtilityHelpers.shuffleArray([1, 2, 3, 4]);
// Output: [2, 4, 1, 3] (random order)
flattenArray(arr)
Flattens nested arrays into a single array.
const flat = UtilityHelpers.flattenArray([1, [2, 3], [4]]);
// Output: [1, 2, 3, 4]
sumArray(arr)
Sums all numeric values in an array.
const sum = UtilityHelpers.sumArray([1, 2, 3]);
// Output: 6
countUniqueElements(arr)
Counts unique elements in an array.
const count = UtilityHelpers.countUniqueElements([1, 2, 2, 3]);
// Output: 3
findDuplicates(arr)
Returns array of duplicate elements.
const duplicates = UtilityHelpers.findDuplicates([1, 2, 2, 3, 3, 4]);
// Output: [2, 3]
countOccurrences(arr, val)
Counts occurrences of a value in an array.
const count = UtilityHelpers.countOccurrences([1, 2, 2, 3], 2);
// Output: 2
getRandomElement(arr)
Selects a random element from an array.
const random = UtilityHelpers.getRandomElement([1, 2, 3, 4, 5]);
// Output: 3 (randomly selected)
getMedian(arr)
Calculates median of numeric array.
const median = UtilityHelpers.getMedian([1, 3, 5, 7, 9]);
// Output: 5
range(start, end, step)
Creates array of numbers in range.
const range = UtilityHelpers.range(1, 10, 2);
// Output: [1, 3, 5, 7, 9]
String Utilities
capitalizeWords(str)
Capitalizes first letter of each word.
const capitalized = UtilityHelpers.capitalizeWords('hello world');
// Output: 'Hello World'
pluralize(word, count)
Pluralizes word based on count, handling irregulars.
const plural = UtilityHelpers.pluralize('child', 2);
// Output: 'children'
escapeHtml(str)
Escapes HTML special characters.
const escaped = UtilityHelpers.escapeHtml('<div>Hello</div>');
// Output: '<div>Hello</div>'
unescapeHtml(str)
Unescapes HTML entities.
const unescaped = UtilityHelpers.unescapeHtml('<div>Hello</div>');
// Output: '<div class="text-gray-900">Hello</div>'
randomString(length)
Generates random alphanumeric string.
const random = UtilityHelpers.randomString(10);
// Output: '7F3g9kL2m1' (random)
numberToWords(num)
Converts number to English words.
const words = UtilityHelpers.numberToWords(123);
// Output: 'one hundred twenty-three'
escapeRegex(str)
Escapes special regex characters.
const safe = UtilityHelpers.escapeRegex('a.b');
// Output: 'a\\.b'
camelCase(str)
Converts string to camelCase.
const str = UtilityHelpers.camelCase('hello-world');
// Output: 'helloWorld'
kebabCase(str)
Converts string to kebab-case.
const str = UtilityHelpers.kebabCase('helloWorld');
// Output: 'hello-world'
snakeCase(str)
Converts string to snake_case.
const str = UtilityHelpers.snakeCase('helloWorld');
// Output: 'hello_world'
truncate(str, length)
Truncates string with ellipsis.
const short = UtilityHelpers.truncate('This is a very long string', 10);
// Output: 'This is a ...'
stripHtml(str)
Removes HTML tags from string.
const text = UtilityHelpers.stripHtml('<p>Hello</p>');
// Output: 'Hello'
Object Utilities
pick(object, keys)
Creates object with only selected keys.
const picked = UtilityHelpers.pick({a: 1, b: 2, c: 3}, ['a', 'c']);
// Output: { a: 1, c: 3 }
omit(object, keys)
Creates object without selected keys.
const omitted = UtilityHelpers.omit({a: 1, b: 2, c: 3}, ['b']);
// Output: { a: 1, c: 3 }
isEqual(a, b)
Performs deep equality check.
const equal = UtilityHelpers.isEqual({a: 1, b: {c: 2}}, {a: 1, b: {c: 2}});
// Output: true
deepMerge(target, source)
Deep merges two objects immutably.
const merged = UtilityHelpers.deepMerge({a: 1}, {b: 2});
// Output: { a: 1, b: 2 }
getType(value)
Returns type: 'array', 'object', or typeof.
const type = UtilityHelpers.getType([1, 2, 3]);
// Output: 'array'
isObjectEmpty(obj)
Checks if object is empty.
const empty = UtilityHelpers.isObjectEmpty({});
// Output: true
Date & Time Utilities
randomDateBetweenTwo(start, end)
Generates random date between two dates.
const date = UtilityHelpers.randomDateBetweenTwo(new Date(2020, 0, 1), new Date());
// Output: Fri Nov 12 2021... (random date)
timeStampID()
Generates unique ID based on timestamp.
const id = UtilityHelpers.timeStampID();
// Output: '1678901234567' (timestamp-based ID)
General Utilities
generateUUID()
Generates a UUID v4.
const uuid = UtilityHelpers.generateUUID();
// Output: 'f47ac10b-58cc-4372-a567-0e02b2c3d479' (valid UUID)
rgbToHex(r, g, b)
Converts RGB to hex color.
const hex = UtilityHelpers.rgbToHex(255, 0, 0);
// Output: '#ff0000'
limitDecimalPlaces(num, places)
Limits decimal places.
const limited = UtilityHelpers.limitDecimalPlaces(1.23456, 2);
// Output: 1.23
generateRandomColor()
Generates random hex color.
const color = UtilityHelpers.generateRandomColor();
// Output: '#a3b2c1' (random hex)
getQueryParams(url)
Parses URL query params into object.
const params = UtilityHelpers.getQueryParams('?a=1&b=2');
// Output: { a: '1', b: '2' }
getURLParts(url)
Breaks down URL into components.
const parts = UtilityHelpers.getURLParts('https://example.com/path?query=value');
// Output: { protocol: 'https:', host: 'example.com', pathname: '/path', search: '?query=value', ... }
shortenURL(url)
Base64-url encodes a URL.
const short = UtilityHelpers.shortenURL('https://example.com');
// Output: 'aHR0cHM6Ly9leGFtcGxlLmNvbQ' (Base64-url encoded)
expandURL(shortenedURL)
Decodes Base64-url encoded URL.
const url = UtilityHelpers.expandURL('aHR0cHM6Ly9leGFtcGxlLmNvbQ');
// Output: 'https://example.com'
levenshteinDistance(str1, str2)
Calculates edit distance between strings.
const distance = UtilityHelpers.levenshteinDistance('kitten', 'sitting');
// Output: 3
clamp(value, min, max)
Clamps a value between min and max.
const clamped = UtilityHelpers.clamp(10, 0, 5);
// Output: 5
parseJSON(str, fallback)
Safely parses JSON with fallback.
const data = UtilityHelpers.parseJSON('bad json', {});
// Output: {} (fallback used)
formatNumber(num, locale)
Formats number with locale info.
const fmt = UtilityHelpers.formatNumber(1234.56);
// Output: '1,234.56' (depends on locale)
formatCurrency(amount, currency, locale)
Formats currency value.
const price = UtilityHelpers.formatCurrency(10.5);
// Output: '$10.50' (depends on locale)
getFileExtension(filename)
Extracts file extension.
const ext = UtilityHelpers.getFileExtension('image.png');
// Output: 'png'
Performance & Optimization
debounce(fn, delay)
Debounces function calls.
const debounced = UtilityHelpers.debounce(() => console.log('called'), 300);
// Output: 'called' (after 300ms of inactivity)
throttle(fn, limit)
Throttles function calls.
const throttled = UtilityHelpers.throttle(() => console.log('called'), 1000);
// Output: 'called' (at most once every 1000ms)
memoize(fn)
Memoizes function results.
const memoized = UtilityHelpers.memoize((x) => x * 2);
console.log(memoized(2)); // Output: 4 (calculated)
console.log(memoized(2)); // Output: 4 (cached)
wait(ms)
Async delay.
await UtilityHelpers.wait(1000);
// Output: (waits for 1000ms)
sleep(ms)
Alias for wait.
await UtilityHelpers.sleep(1000);
// Output: (waits for 1000ms)
retry(fn, attempts, delay)
Retries async function with backoff.
await UtilityHelpers.retry(fetchData, 3, 1000);
// Output: (result of fetchData after successful attempt)
once(fn)
Ensures function runs only once.
const init = UtilityHelpers.once(() => console.log('Init'));
init(); // Output: 'Init'
init(); // Output: (nothing)
pipe(...fns)
Pipes functions left-to-right.
const flow = UtilityHelpers.pipe(x => x + 1, x => x * 2);
console.log(flow(1)); // Output: 4 ((1 + 1) * 2)
compose(...fns)
Composes functions right-to-left.
const flow = UtilityHelpers.compose(x => x + 1, x => x * 2);
console.log(flow(1)); // Output: 3 ((1 * 2) + 1)
Validation & Sanitization
isValidEmail(email)
Validates email format.
const valid = UtilityHelpers.isValidEmail('test@example.com');
// Output: true
isValidURL(url)
Validates URL format.
const valid = UtilityHelpers.isValidURL('https://example.com');
// Output: true
validateAndSanitizeInput(inputElement, type, options)
Validates and sanitizes form input.
const result = UtilityHelpers.validateAndSanitizeInput(emailInput, 'email');
// Output: { valid: true, sanitized: 'test@example.com' }
DOM & UI Utilities
copyToClipboard(text)
Copies text to clipboard.
UtilityHelpers.copyToClipboard('Hello');
// Output: (text 'Hello' copied to clipboard)
smoothScrollTo(selector)
Smooth scrolls to element.
UtilityHelpers.smoothScrollTo('#top');
// Output: (page scrolls to element with id 'top')
toggleClassAfterDelay(element, className, delay)
Toggles class after delay.
UtilityHelpers.toggleClassAfterDelay(el, 'active', 1000);
// Output: (class 'active' added/removed after 1000ms)
detectUserIdleTime(callback, idleTime)
Detects user idle time.
UtilityHelpers.detectUserIdleTime(() => console.log('Idle'), 5000);
// Output: 'Idle' (after 5 seconds of no activity)
getFormData(formElement)
Extracts form data as object.
const data = UtilityHelpers.getFormData(formElement);
// Output: { name: 'John', email: 'john@example.com' }
downloadFile(blob, filename)
Triggers file download.
UtilityHelpers.downloadFile('content', 'file.txt', 'text/plain');
// Output: (triggers browser download of 'file.txt')
toggleFullscreen(element)
Toggles fullscreen mode.
UtilityHelpers.toggleFullscreen(document.documentElement);
// Output: (toggles fullscreen mode)
lazyLoadImages(selector)
Lazy loads images on scroll.
UtilityHelpers.lazyLoadImages('.lazy');
// Output: (sets up intersection observer for '.lazy' images)
getCSSVariable(variableName, element)
Gets CSS variable value.
const color = UtilityHelpers.getCSSVariable('--primary-color');
// Output: '#3b82f6' (value of custom property)
setCSSVariable(variableName, value, element)
Sets CSS variable value.
UtilityHelpers.setCSSVariable('--primary-color', '#ff0000');
// Output: (updates --primary-color to red)
saveScrollPosition()
Saves current scroll position.
UtilityHelpers.saveScrollPosition();
// Output: (saves current scrollY to localStorage)
restoreScrollPosition()
Restores saved scroll position.
UtilityHelpers.restoreScrollPosition();
// Output: (restores scrollY from localStorage)
textToSpeech(text)
Speaks text using SpeechSynthesis with options.
UtilityHelpers.textToSpeech('Hello World', {
rate: 1.2, // 0.1 to 10
pitch: 1, // 0 to 2
volume: 1, // 0 to 1
voice: 'Google US English' // Optional voice name
});
// Output: (speaks 'Hello World' with specified settings)
getVoices()
Returns available speech synthesis voices.
const voices = UtilityHelpers.getVoices();
// Output: [SpeechSynthesisVoice, SpeechSynthesisVoice, ...]
debouncedInput(inputElement, callback, delay)
Debounces input events.
UtilityHelpers.debouncedInput(input, () => console.log('input'), 300);
// Output: 'input' (after 300ms of no typing)
runInParallel(tasks)
Runs async tasks in parallel.
const results = await UtilityHelpers.runInParallel([task1, task2]);
// Output: [result1, result2]