npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

roks-jsh

v0.1.2

Published

A comprehensive collection of JavaScript helper utilities for everyday development tasks

Downloads

8

Readme

roks-jsh

CI/CD npm version License: MIT

A comprehensive collection of JavaScript helper utilities for everyday development tasks. Features 492+ tests across 26 modules covering basic utilities, async operations, arrays, strings, numbers, password validation, object manipulation, file paths, colors, and URL processing.

Installation

npm install roks-jsh

Usage

ES Module import:

import { isEmpty, clamp, debounce } from 'roks-jsh';

console.log(isEmpty('')); // true
console.log(clamp(10, 0, 5)); // 5

CommonJS import:

const { isEmpty, validatePassword } = require('roks-jsh');

Default import (all utilities):

import utils from 'roks-jsh';
utils.isEmpty(''); // true

Features

  • 492+ tests with comprehensive coverage across 26 modules
  • Full TypeScript support with type definitions
  • Tree-shakable - import only what you need
  • Zero dependencies - pure JavaScript utilities
  • ESM & CommonJS compatible
  • Async utilities with cancellation support and promise helpers
  • Advanced array operations with type-safe searching and chunking
  • String manipulation with case conversion, masking, and validation
  • Number utilities including math operations and prime checking
  • Password security validation and strength checking
  • Deep object operations with path-based access and merging
  • File path utilities for cross-platform path handling
  • Color manipulation with hex/RGB/HSL conversion and contrast checking
  • URL processing with parsing, building, and validation
  • Crypto utilities with hashing, encoding, and random generation
  • Error handling with custom error classes and retry logic

Development

Setup

npm install

Testing

npm test          # Run all tests
npm run test:watch # Run tests in watch mode

Building

npm run build     # Build for production
npm run lint      # Lint code

Publishing

npm run prepublishOnly  # Runs tests and build before publish

API Reference (selected)

Below are some of the most useful functions in this package. See the src/ tree for full TypeScript types. re

  • isEmpty(value) — returns true for null, undefined, empty string, empty array, or empty object.
  • clamp(value, min, max) — clamps number between min and max.
  • debounce(fn, wait, atStart=false) — returns a debounced function. When atStart is true, the function executes immediately on the first call and then debounces further calls.
  • throttle(fn, wait, { leading=true, trailing=false }) — throttles a function and supports leading/trailing options.
  • asyncDelay(ms) — returns a Promise that resolves after ms milliseconds.
  • CancellationTokenSource / CancellationToken — .NET-like cooperative cancellation primitives.

arrayAdvancedSearcher(rows, conditions, options?)

Powerful, type-safe search/filter helper for arrays of objects.

Signature (TS):

arrayAdvancedSearcher<T extends Record<string, any>>(rows: T[], conditions: Condition<T>[], options?: { caseSensitive?: boolean }): T[]

Features:

  • Multiple condition types: text operators (includes, equals, startsWith, endsWith, regex) and numeric operators (eq, ne, gt, gte, lt, lte).
  • exists operator to test for presence or absence of a key.
  • Logical OR groups using { anyOf: [ ...conditions ] }. Top-level conditions are ANDed.
  • Case-insensitive by default (pass { caseSensitive: true } to change).

Example:

const data = [
	{ name: 'Alice', age: 25, city: 'New York' },
	{ name: 'Bob', age: 30, city: 'Los Angeles' },
];

// Find people named Alice or living in New York
const results = arrayAdvancedSearcher(data, [
	{ anyOf: [ { key: 'name', op: 'equals', value: 'Alice' }, { key: 'city', op: 'equals', value: 'New York' } ] }
]);

// Numeric filter: find adults (age >= 18)
const adults = arrayAdvancedSearcher(data, [ { key: 'age', op: 'gte', value: 18 } ]);
const adults = arrayAdvancedSearcher(data, [ { key: 'age', op: 'gte', value: 18 } ]);

Contributing

PRs welcome! Please:

  1. Run npm test and ensure all tests pass
  2. Add tests for new features
  3. Update documentation in README.md
  4. Follow existing code style and patterns

License

MIT - see LICENSE file for details.


Full API Reference

This section lists all public exports from the library with short descriptions and examples. Use the TypeScript source in src/ for full signatures.

isEmpty(value)

  • Returns true for null, undefined, empty string (after trim), empty array, or plain object with no keys.

Example:

import { isEmpty } from 'roks-jsh';
isEmpty(''); // true
isEmpty([]); // true
isEmpty({}); // true

clamp(n, min = 0, max = 1)

  • Clamp a number to the inclusive range [min, max].

Example:

import { clamp } from 'roks-jsh';
clamp(10, 0, 5); // 5

debounce(fn, wait = 100, atStart = false)

  • Returns a debounced wrapper around fn. If atStart is true, the first call runs immediately (leading) and subsequent calls are suppressed until wait passes.

Example:

import { debounce } from 'roks-jsh';
const deb = debounce(() => console.log('run'), 200);
deb(); deb(); // only one run after 200ms

const debImmediate = debounce(() => console.log('now'), 200, true);
debImmediate(); // logs immediately

throttle(fn, wait = 100, { leading = true, trailing = false })

  • Throttle a function. leading triggers at the start of the window, trailing triggers at the end if calls occurred.

Example:

import { throttle } from 'roks-jsh';
const t = throttle(()=>console.log('tick'), 100, { leading: true, trailing: true });
t(); t(); // runs immediately and once more after the window

chunkArray(array, chunkSize)

  • Split an array into chunks of size chunkSize (last chunk may be smaller). Throws when chunkSize <= 0.

Example:

import { chunkArray } from 'roks-jsh';
chunkArray([1,2,3,4,5], 2); // [[1,2],[3,4],[5]]

arrayAdvancedSearcher(rows, conditions, options?)

  • Advanced, typed search/filter helper. Conditions support text operators (includes, equals, startsWith, endsWith, regex), numeric operators (eq, ne, gt, gte, lt, lte) and exists.
  • Use { anyOf: [...] } to create OR groups. Top-level conditions are ANDed.

Example:

import { arrayAdvancedSearcher } from 'roks-jsh';

const people = [ {name:'Alice', age:25}, {name:'Bob', age:30} ];
// name contains 'li' OR age >= 30
const res = arrayAdvancedSearcher(people, [ { anyOf: [ { key: 'name', op: 'includes', value: 'li' }, { key: 'age', op: 'gte', value: 30 } ] } ]);

asyncDelay(ms)

  • Returns a Promise that resolves after ms milliseconds. Useful in async workflows and tests.

Example:

import { asyncDelay } from 'roks-jsh';
await asyncDelay(100); // wait 100ms

random utilities

  • randomInt(min, max, useCrypto = true) — integer in [min, max], uses crypto when available.
  • randomFloat(min, max, inclusive = false) — float in [min, max).
  • randomString(length = 7, alphabet?, useCrypto = true) — random string.
  • randomHex(length = 6, useCrypto = true) — random hex string of given length.

Example:

import { randomInt, randomString } from 'roks-jsh';
randomInt(0, 10); // e.g. 7
randomString(8); // e.g. 'a4f2k8q1'

TimeCounter and CounterObject

  • CounterObject is a simple counter with count, tickUp, tickDown, reset, increment, decrement.
  • TimeCounter extends CounterObject with time helpers (totalSeconds, totalMinutes, totalHours, hours, minutes, seconds, toString(), toJSON()) and static fromTime(h,m,s) constructor.

Example:

import TimeCounter from 'roks-jsh';
const t = TimeCounter.fromTime(1, 30, 15); // 1:30:15
console.log(t.toString());

CancellationTokenSource / CancellationToken

  • .cancel(reason?) — cancel immediately.
  • .cancelAfter(ms, reason?) — schedule cancellation.
  • token.isCancellationRequested — boolean state.
  • token.register(cb) — register cleanup callback, returns { dispose() }.
  • token.promise resolves when cancellation occurs (with optional reason).

Example:

import { CancellationTokenSource } from 'roks-jsh';
const cts = new CancellationTokenSource();
cts.token.register(() => console.log('cancelled'));
cts.cancelAfter(5000, 'timeout');

AsyncSetInterval(callback, ms = 1000, errorHalt = false, errorRun?, ...args)

  • Runs an async callback repeatedly, waiting ms between calls. Returns { cancel(), isRunning } and supports cancellation with the library's CancellationToken.

Example:

import { AsyncSetInterval } from 'roks-jsh';
const interval = AsyncSetInterval(async () => {
	// do work
}, 1000);
// stop later
interval.cancel();

maskString(str, options?)

  • Mask parts of a string for privacy (e.g., credit cards, passwords). Options: start=0, end=0, maskChar='*', maskLength?.

Example:

import { maskString } from 'roks-jsh';
maskString('1234567890', { start: 0, end: 4 }); // '******7890'

sortObjects(array, key, options?)

  • Sort an array of objects by a key. Options: descending=false, caseInsensitive=true, nullsFirst=false.

Example:

import { sortObjects } from 'roks-jsh';
const people = [{name:'Bob'}, {name:'Alice'}];
sortObjects(people, 'name'); // [{name:'Alice'}, {name:'Bob'}]

String Utilities

  • capitalize(str) — capitalize first letter, lowercase rest.
  • camelCase(str) — convert to camelCase.
  • kebabCase(str) — convert to kebab-case.
  • snakeCase(str) — convert to snake_case.
  • pascalCase(str) — convert to PascalCase.
  • titleCase(str) — convert to Title Case.
  • truncate(str, length, suffix='...') — truncate string with suffix.
  • padStart(str, targetLength, padString=' ') — pad start of string.
  • padEnd(str, targetLength, padString=' ') — pad end of string.
  • reverse(str) — reverse string.
  • repeat(str, count) — repeat string n times.
  • isBlank(str) — check if string is blank (empty or whitespace).
  • removeWhitespace(str) — remove all whitespace.
  • countWords(str) — count words in string.
  • slugify(str) — create URL-friendly slug.
  • startsWithIgnoreCase(str, search) — case-insensitive startsWith.
  • endsWithIgnoreCase(str, search) — case-insensitive endsWith.
  • includesIgnoreCase(str, search) — case-insensitive includes.

Example:

import { camelCase, slugify, truncate } from 'roks-jsh';
camelCase('hello world'); // 'helloWorld'
slugify('Hello, World!'); // 'hello-world'
truncate('very long text', 10); // 'very long...'

Number Utilities

  • isEven(n) — check if number is even.
  • isOdd(n) — check if number is odd.
  • isPrime(n) — check if number is prime.
  • isPerfectSquare(n) — check if number is a perfect square.
  • isInteger(n) — check if number is an integer.
  • isPositive(n) — check if number is positive.
  • isNegative(n) — check if number is negative.
  • isZero(n) — check if number is zero.

Example:

import { isPrime, isEven } from 'roks-jsh';
isPrime(7); // true
isEven(4); // true

Math Utilities

  • roundTo(n, decimals=0) — round number to specified decimal places.
  • clampRange(value, min, max) — clamp value to range [min, max].
  • clampPercentage(value) — clamp value to range [0, 100].
  • lerp(start, end, t) — linear interpolation between start and end (t clamped to [0, 1]).
  • mapRange(value, fromMin, fromMax, toMin, toMax) — map value from one range to another.
  • percentage(value, total, decimals=2) — calculate percentage with optional decimal precision.
  • isBetween(value, min, max) — check if value is between min and max (inclusive).
  • average(numbers) — calculate average of array of numbers.
  • median(numbers) — calculate median of array of numbers.
  • sum(numbers) — calculate sum of array of numbers.
  • min(numbers) — find minimum value in array.
  • max(numbers) — find maximum value in array.
  • factorial(n) — calculate factorial of n.
  • gcd(a, b) — calculate greatest common divisor.
  • lcm(a, b) — calculate least common multiple.
  • degreesToRadians(degrees) — convert degrees to radians.
  • radiansToDegrees(radians) — convert radians to degrees.

Example:

import { clampRange, lerp, mapRange, percentage } from 'roks-jsh';
clampRange(15, 0, 10); // 10
lerp(0, 100, 0.5); // 50
mapRange(5, 0, 10, 0, 100); // 50
percentage(25, 200); // 12.5

Password Validation

  • hasMinLength(password, min=8) — check minimum length.
  • hasUppercase(password) — check for uppercase letters.
  • hasLowercase(password) — check for lowercase letters.
  • hasNumbers(password) — check for numbers.
  • hasSpecialChars(password) — check for special characters.
  • isNotCommon(password) — check against common passwords.
  • hasNoSequential(password) — check for sequential characters.
  • hasNoRepeated(password) — check for repeated characters.
  • calculatePasswordStrength(password) — calculate strength score (0-100).
  • getStrengthCategory(score) — get category ('weak', 'fair', 'good', 'strong').
  • validatePassword(password, options?) — validate with multiple criteria.

Example:

import { validatePassword, calculatePasswordStrength } from 'roks-jsh';
const result = validatePassword('MySecure123!');
console.log(result.isValid); // true
console.log(calculatePasswordStrength('weak')); // low score

Object Utilities

  • deepClone(obj) — deep clone objects, arrays, dates, primitives.
  • deepMerge(target, source) — deeply merge objects.
  • pick(obj, keys) — pick specified properties from object.
  • omit(obj, keys) — omit specified properties from object.
  • isEqual(a, b) — deep equality comparison.
  • get(obj, path) — get nested value by path (dot notation or array).
  • set(obj, path, value) — set nested value by path.
  • has(obj, path) — check if path exists in object.
  • defaults(obj, defaults) — fill missing properties with defaults.

Example:

import { deepClone, pick, get, set } from 'roks-jsh';
const obj = { a: { b: 1 } };
const clone = deepClone(obj);
const picked = pick(obj, ['a']);
const value = get(obj, 'a.b'); // 1
set(obj, 'a.c', 2); // obj.a.c = 2

URL Utilities

  • parseUrl(url) — parse URL into components (protocol, hostname, port, etc.).
  • isValidUrl(url) — validate URL format.
  • isSecureUrl(url) — check if URL uses HTTPS.
  • getDomain(url) — extract domain from URL.
  • getPathname(url) — extract pathname from URL.
  • getPort(url) — extract port (null for default ports).
  • getQueryParams(url) — parse query parameters into object.
  • buildUrl(base, params) — build URL with query parameters.
  • setQueryParams(url, params) — set query parameters on URL.
  • removeQueryParams(url, keys) — remove query parameters from URL.
  • getQueryParam(url, key) — get specific query parameter value.
  • hasQueryParam(url, key) — check if query parameter exists.
  • cleanUrl(url, paramsToRemove?) — clean URL by removing hash and query params.
  • getOrigin(url) — get origin (protocol + host).
  • isSameOrigin(url1, url2) — check if URLs have same origin.
  • getUrlExtension(url) — get file extension from URL.
  • isImageUrl(url) — check if URL points to an image.

Example:

import { parseUrl, buildUrl, getQueryParams, isValidUrl } from 'roks-jsh';

// Parse URL
const parsed = parseUrl('https://example.com/path?param=value');
console.log(parsed?.hostname); // 'example.com'

// Build URL with params
const url = buildUrl('https://api.example.com/search', { q: 'javascript', limit: 10 });

// Parse query params
const params = getQueryParams('https://example.com?a=1&b=2&c=3');

// Validate URL
console.log(isValidUrl('https://example.com')); // true

Color Utilities

  • hexToRgb(hex) — convert hex color to RGB object.
  • rgbToHex(r, g, b) — convert RGB values to hex string.
  • rgbToHexFromObject(rgb) — convert RGB object to hex string.
  • isValidHex(hex) — validate hex color format.
  • lighten(hex, amount) — lighten hex color by percentage.
  • darken(hex, amount) — darken hex color by percentage.
  • getContrastRatio(color1, color2) — calculate contrast ratio between two colors.
  • meetsContrastStandard(color1, color2, standard) — check if colors meet WCAG contrast standards.
  • rgbToHsl(r, g, b) — convert RGB to HSL.
  • hslToRgb(h, s, l) — convert HSL to RGB.
  • randomColor() — generate random hex color.
  • mixColors(color1, color2, weight) — mix two colors with specified weight.
  • invertColor(hex) — invert hex color.
  • grayscale(hex) — convert color to grayscale.

Example:

import { hexToRgb, lighten, getContrastRatio, randomColor } from 'roks-jsh';

const rgb = hexToRgb('#ff0000'); // { r: 255, g: 0, b: 0 }
const lighter = lighten('#3366cc', 20); // '#5c85e6'
const contrast = getContrastRatio('#000000', '#ffffff'); // 21
const random = randomColor(); // e.g. '#a4f2k8'

File Path Utilities

  • getFileExtension(path) — get file extension from path.
  • getFilename(path) — get filename from path.
  • getDirectory(path) — get directory from path.
  • joinPath(...segments) — join path segments.
  • normalizePath(path) — normalize path separators and resolve . and ..
  • isAbsolutePath(path) — check if path is absolute.
  • resolvePath(relativePath, basePath) — resolve relative path against base path.
  • getRelativePath(from, to) — get relative path from one path to another.
  • hasExtension(filename, extensions) — check if file has one of the specified extensions.
  • changeExtension(filename, newExtension) — change file extension.
  • formatFileSize(bytes, decimals) — format bytes to human readable size.
  • isDirectoryPath(path) — check if path is a directory path.
  • sanitizeFilename(filename, replacement) — sanitize filename by removing invalid characters.
  • getMimeType(filename) — get MIME type based on file extension.

Example:

import { getFileExtension, joinPath, normalizePath, hasExtension } from 'roks-jsh';

getFileExtension('document.pdf'); // 'pdf'
joinPath('folder', 'subfolder', 'file.txt'); // 'folder/subfolder/file.txt'
normalizePath('./folder/../file.txt'); // 'file.txt'
hasExtension('image.png', ['jpg', 'png', 'gif']); // true

Crypto Utilities

  • hash(data, algorithm) — hash data with specified algorithm.
  • hashWithSalt(data, salt, algorithm) — hash data with salt.
  • generateSalt(length) — generate random salt string.
  • xorCipher(text, key) — encrypt/decrypt text with XOR cipher.
  • base64Encode(input) — encode string to base64.
  • base64Decode(input) — decode base64 to string.
  • generateUUID() — generate UUID v4.
  • randomPick(array) — pick random element from array.
  • randomBool(probability) — return random boolean with specified probability.

Example:

import { hash, generateSalt, base64Encode, generateUUID } from 'roks-jsh';

const hashed = hash('password', 'sha256');
const salt = generateSalt(16);
const encoded = base64Encode('hello world');
const uuid = generateUUID(); // e.g. '550e8400-e29b-41d4-a716-446655440000'

Collection Utilities

  • groupBy(array, keyFn) — group array elements by key function.
  • sortBy(array, keyFn, descending) — sort array by key function.
  • unique(array, keyFn) — remove duplicates from array.
  • intersection(array1, array2, keyFn) — find intersection of two arrays.
  • difference(array1, array2, keyFn) — find difference of two arrays.
  • chunk(array, size) — split array into chunks.
  • union(array1, array2, keyFn) — find union of two arrays.
  • partition(array, predicate) — partition array into two arrays based on predicate.
  • countBy(array, keyFn) — count occurrences of each key.
  • minBy(array, keyFn) — find minimum element by key function.
  • maxBy(array, keyFn) — find maximum element by key function.
  • colShuffle(array) — shuffle array elements.
  • take(array, n) — take first n elements.
  • drop(array, n) — drop first n elements.
  • takeRight(array, n) — take last n elements.
  • dropRight(array, n) — drop last n elements.

Example:

import { groupBy, unique, chunk, take, colShuffle } from 'roks-jsh';

const grouped = groupBy([{type: 'A', value: 1}, {type: 'B', value: 2}, {type: 'A', value: 3}], item => item.type);
const deduped = unique([1, 2, 2, 3, 3, 3]); // [1, 2, 3]
const chunks = chunk([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]]
const firstThree = take([1, 2, 3, 4, 5], 3); // [1, 2, 3]
const shuffled = colShuffle([1, 2, 3, 4, 5]); // e.g. [3, 1, 5, 2, 4]

Function Utilities

  • fnMemoize(fn, options) — memoize function results.
  • fnOnce(fn) — ensure function runs only once.
  • fnRetry(fn, options) — retry function on failure.
  • fnDebounce(fn, wait, options) — debounce function calls.
  • fnThrottle(fn, wait, options) — throttle function calls.
  • fnDelay(fn, wait) — delay function execution.
  • fnAfter(fn, n) — execute function after n calls.
  • fnBefore(fn, n) — execute function only for first n calls.
  • fnNegate(predicate) — negate predicate function.
  • fnConstant(value) — return constant value function.
  • fnIdentity(value) — return input value function.
  • Aliases: memoize (fnMemoize), once (fnOnce), retryFunction (fnRetry), after (fnAfter), before (fnBefore), negate (fnNegate), constant (fnConstant), identity (fnIdentity).

Example:

import { fnMemoize, fnOnce, fnRetry, fnDebounce } from 'roks-jsh';

const memoized = fnMemoize((x) => x * x);
memoized(5); // calculated
memoized(5); // cached result

const once = fnOnce(() => console.log('runs once'));
once(); once(); // only logs once

const retry = fnRetry(() => fetch('api'), { attempts: 3 });
const debounced = fnDebounce(() => console.log('debounced'), 300);

Validation Utilities

  • isValidEmail(email) — validate email format.
  • isValidPhone(phone) — validate phone number.
  • isValidCreditCard(cardNumber) — validate credit card number.
  • isValidUUID(uuid) — validate UUID format.
  • isValidJSON(json) — validate JSON string.
  • isValidBase64(base64) — validate base64 string.
  • isValidIPv4(ip) — validate IPv4 address.
  • isValidIPv6(ip) — validate IPv6 address.
  • isValidPostalCode(postalCode, country) — validate postal code by country.
  • isValidPassword(password, options) — validate password strength.

Example:

import { isValidEmail, isValidPhone, isValidUUID, isValidPassword } from 'roks-jsh';

isValidEmail('[email protected]'); // true
isValidPhone('+1-555-123-4567'); // true
isValidUUID('550e8400-e29b-41d4-a716-446655440000'); // true
isValidPassword('MySecure123!', { minLength: 8 }); // true

Error Utilities

  • CustomError(message, code, status) — create custom error with code and status.
  • ValidationError(message) — error for validation failures.
  • AuthenticationError(message) — error for authentication failures.
  • AuthorizationError(message) — error for authorization failures.
  • NotFoundError(message) — error for not found resources.
  • ConflictError(message) — error for conflicts.
  • RateLimitError(message, retryAfter) — error for rate limiting.
  • NetworkError(message) — error for network issues.
  • TimeoutError(message) — error for timeouts.
  • parseError(error) — parse error into standardized format.
  • createRetryableError(context) — create error with retry context.
  • extractStackTrace(error) — extract stack trace lines.
  • parseStackFrame(frame) — parse stack frame string.
  • getCallStack() — get current call stack.
  • isRetryableError(error) — check if error is retryable.
  • withErrorHandling(fn, logger) — wrap function with error handling.
  • withErrorBoundary(asyncFn, fallback) — wrap async function with error boundary.
  • aggregateErrors(errors) — aggregate multiple errors.
  • formatError(error, options) — format error for display.

Example:

import { CustomError, ValidationError, isRetryableError, withErrorHandling } from 'roks-jsh';

throw new CustomError('Something went wrong', 'CUSTOM_ERROR', 400);
throw new ValidationError('Invalid input');

const result = withErrorHandling(
  () => riskyOperation(),
  (error) => console.error('Handled:', error)
);

Promise Utilities

  • retry(asyncFn, options) — retry async function on failure.
  • timeout(asyncFn, ms, timeoutMessage) — add timeout to async function.
  • parallel(tasks, concurrency) — execute tasks in parallel with concurrency limit.
  • raceWithTimeout(tasks, timeout) — race multiple promises with timeout.
  • delay(ms, value) — create delay promise.
  • sequence(tasks) — execute promises in sequence.
  • delayReject(ms, rejectAfter, value) — delay rejection.
  • withProgress(asyncFn, onProgress) — track progress of async operation.

Example:

import { retry, timeout, parallel, delay, sequence } from 'roks-jsh';

const result = await retry(() => fetch('api'), { attempts: 3 });
const timed = await timeout(fetch('slow-api'), 5000);
const results = await parallel([task1, task2, task3], 2);
await delay(1000); // wait 1 second
const sequenced = await sequence([step1, step2, step3]);

Exports

Named exports (recommended for tree-shaking):

import { isEmpty, debounce, arrayAdvancedSearcher, validatePassword } from 'roks-jsh';

Default export (all utilities in one object):

import utils from 'roks-jsh';
utils.isEmpty(''); // true

Available utilities by category:

  • Basic: isEmpty, clamp
  • Async: debounce, throttle, asyncDelay, CancellationTokenSource, CancellationToken, AsyncSetInterval
  • Arrays: chunkArray, arrayAdvancedSearcher, sortObjects
  • Random: randomInt, randomHex, randomString, randomFloat
  • Time: TimeCounter, CounterObject
  • Strings: maskString, capitalize, camelCase, kebabCase, snakeCase, pascalCase, titleCase, truncate, padStart, padEnd, reverse, repeat, isBlank, removeWhitespace, countWords, slugify, startsWithIgnoreCase, endsWithIgnoreCase, includesIgnoreCase, numberToWords, wordsToNumber
  • Numbers: isEven, isOdd, isPrime, isPerfectSquare, isInteger, isPositive, isNegative, isZero
  • Math: roundTo, clampRange, clampPercentage, lerp, mapRange, percentage, isBetween, average, median, sum, min, max, factorial, gcd, lcm, degreesToRadians, radiansToDegrees
  • Colors: hexToRgb, rgbToHex, rgbToHexFromObject, isValidHex, lighten, darken, getContrastRatio, meetsContrastStandard, rgbToHsl, hslToRgb, randomColor, mixColors, invertColor, grayscale
  • File Paths: getFileExtension, getFilename, getDirectory, joinPath, normalizePath, isAbsolutePath, resolvePath, getRelativePath, hasExtension, changeExtension, formatFileSize, isDirectoryPath, sanitizeFilename, getMimeType
  • Crypto: hash, hashWithSalt, generateSalt, xorCipher, base64Encode, base64Decode, generateUUID, randomPick, randomBool
  • Collections: groupBy, sortBy, unique, intersection, difference, chunk, union, partition, countBy, minBy, maxBy, colShuffle, take, drop, takeRight, dropRight
  • Functions: fnMemoize, fnOnce, fnRetry, fnDebounce, fnThrottle, fnDelay, fnAfter, fnBefore, fnNegate, fnConstant, fnIdentity, memoize, once, retryFunction, after, before, negate, constant, identity
  • Validation: isValidEmail, isValidPhone, isValidCreditCard, isValidUUID, isValidJSON, isValidBase64, isValidIPv4, isValidIPv6, isValidPostalCode, isValidPassword
  • Errors: CustomError, ValidationError, AuthenticationError, AuthorizationError, NotFoundError, ConflictError, RateLimitError, NetworkError, TimeoutError, parseError, createRetryableError, extractStackTrace, parseStackFrame, getCallStack, isRetryableError, withErrorHandling, withErrorBoundary, aggregateErrors, formatError
  • Promises: retry, timeout, parallel, raceWithTimeout, delay, sequence, delayReject, withProgress
  • Password: hasMinLength, hasUppercase, hasLowercase, hasNumbers, hasSpecialChars, isNotCommon, hasNoSequential, hasNoRepeated, calculatePasswordStrength, getStrengthCategory, validatePassword
  • Objects: deepClone, deepMerge, pick, omit, isEqual, get, set, has, defaults
  • URLs: parseUrl, isValidUrl, isSecureUrl, getDomain, getPathname, getPort, getQueryParams, buildUrl, setQueryParams, removeQueryParams, getQueryParam, hasQueryParam, cleanUrl, getOrigin, isSameOrigin, getUrlExtension, isImageUrl

Built with ❤️ using TypeScript, Vitest, and Rollup. All utilities are pure functions with no side effects.