A collection of convenient JavaScript utilities.
npm install @tmbr/utilsA collection of convenient JavaScript utilities.
``bash`
npm install @tmbr/utils
Breaking changes introduced in version 2.0.0:
* request headers param is now fetch options (allows cancellation via AbortController)io
* function signature changeparse
* is now toJSONsetProperty
* is now prop and no longer falls back to the root html element if value is ommittedcreateWorker
* is now worker
#### Table of Contents
* attr
* average
* bind
* brightness
* clamp
* combine
* cookie
* coords
* cx
* debounce
* distance
* dot
* empty
* fill
* findAll
* findOne
* focusables
* format
* html
* indexOf
* io
* isArray
* isBoolean
* isClass
* isDefined
* isElement
* isEmpty
* isFunction
* isIterator
* isNumber
* isNumeric
* isObject
* isString
* isUndefined
* lerp
* luminance
* map
* noop
* normalize
* observable
* on
* only
* once
* ordinal
* PI
* pipe
* pledge
* pluck
* prop
* random
* rect
* request
* ro
* round
* safe
* settled
* shuffle
* slug
* svg
* throttle
* toArray
* toBoolean
* toJSON
* toDegrees
* toRadians
* toRelativeTime
* toRGB
* trap
* traverse
* uid
* validate
* wait
* worker
* wrap
Gets, sets or removes an attribute from an element
#### Parameters
* el Element elementname
* string attribute namevalue
* (string | boolean) attribute value (falsy to remove)
Returns (string | undefined) attribute value when getting
Calculates the average from an array of numbers
#### Parameters
* values Array<number> array of numbers
Returns number average value
Binds methods to an instance, including class getters and setters (based on auto-bind)
#### Parameters
* self Object target instancemethods
* (string | Array<string>) specific method name(s) to bind, or omit for all
#### Examples
`javascript`
class Example {
constructor() { bind(this); }
}
Returns Object self for chaining
Calculates perceived brightness from an RGB array
#### Parameters
* rgb Array<number> \[r, g, b] values (0-255)
Returns number brightness value (0-255)
Clamps a value between two bounds
#### Parameters
* value number value to clampmin
* number minimum boundary (default: 0) (optional, default 0)max
* number maximum boundary (default: 1) (optional, default 1)
Returns number clamped value
Combines multiple functions into a single callback that calls all of them
#### Parameters
* fns ...Function functions to combine
Returns Function combined function
Gets, sets, or deletes a cookie
#### Parameters
* name string cookie namevalue
* (string | null) value to set, or null to deleteoptions
* (number | Date | Object) expiration days, Date, or cookie attributes
#### Examples
`javascript`
cookie('name', 'value'); // set
cookie('name'); // get
cookie('name', null); // delete
cookie('name', 'value', 30); // expires in 30 days
Returns (string | undefined) cookie value when getting
Gets x and y coordinates from a pointer event, optionally relative to a target element
#### Parameters
* event Event mouse or touch eventtarget
* Element optional element for relative coordinates
Returns Object object with x, y (and px, py percentages if target provided)
Conditionally toggles classes on an element or generates a string of classes,
similar to classnames
#### Parameters
* args ...(string | Object | Array) class names, objects, or arraysel
* Element optional element to modify
#### Examples
`javascript`
cx('a', {'b': false, 'c': true}, [null && 'd', 'e']); // 'a c e'
cx(el, 'active', {'visible': isVisible});
Returns (string | DOMTokenList) class string, or classList if element passed with no args
Creates a debounced function that delays invocation until after wait ms have elapsed
since the last call
#### Parameters
* fn Function function to debouncewait
* number delay in milliseconds
#### Examples
`javascript`
const debouncedFn = debounce(onInput, 300);
Returns Function debounced function
Calculates the distance between two points
#### Parameters
* x1 (number | Object) x coordinate or object with x and y propertiesy1
* (number | Object) y coordinate or object with x and y propertiesx2
* number x coordinate of the second point (when using coordinates)y2
* number y coordinate of the second point (when using coordinates)
Returns number distance
Gets or sets a value at a dot-notated path within a nested object
#### Parameters
* object Object target objectpath
* string dot-notated path (e.g., 'a.b.c')value
* any value to set (omit to get)
#### Examples
`javascript`
dot(obj, 'user.name'); // get
dot(obj, 'user.name', 'Nik'); // set
Returns any nested value when getting, or object when setting
Removes all children from an element (can be significantly faster than innerHTML)
#### Parameters
* el Element element to empty
#### Examples
`javascript`
const div = document.querySelector('.example');
empty(div).append(fragment);
Returns Element the emptied element for chaining
Creates an array of specified length filled with values
#### Parameters
* n number array lengthvalue
* (any | Function) fill value, or function receiving index
Returns Array filled array
querySelectorAll wrapper with optional parent context
#### Parameters
* selector string CSS selectorparent
* Element parent element (default: document)
Returns Array<Element> array of matching elements
querySelector wrapper with optional parent context
#### Parameters
* selector string CSS selectorparent
* Element parent element (default: document)
Returns (Element | null) matching element or null
Array of CSS selectors for focusable elements based on focusable-selectors
Formats a date according to a pattern string
#### Parameters
* pattern string format pattern (YYYY, MM, DD, HH, mm, ss, etc.)date
* (Date | string | number) date to format (default: now)
#### Examples
`javascript`
format('MMMM Do, YYYY'); // 'January 1st, 2024'
format('YYYY-MM-DD', someDate); // '2024-01-01'
Returns string formatted date string
Creates DOM elements using template literals, inspired by facon
#### Parameters
* strings TemplateStringsArray template literal stringsvars
* ...any template literal values (strings, elements, or arrays)
#### Examples
`javascript
const img = html
;
const list = html
- ${i}
)};
`Returns (Element | DocumentFragment) single element or fragment if multiple root nodes
$3
Gets the index of an element among its siblings
#### Parameters
*
el Element element to find index ofReturns number index within parent's children
$3
Tracks enter and leave events on an element using IntersectionObserver
#### Parameters
*
el Element element to observe
* options Object enter/leave callbacks, once boolean, and IntersectionObserver options *
options.enter
* options.leave
* options.once (optional, default false)
* options.rest ...any #### Examples
`javascript
const unobserve = io(el, {
enter: () => console.log('enter'),
leave: () => console.log('leave'),
});
`Returns Function cleanup function to stop observing
$3
Checks if a value is an array using Array.isArray)
#### Parameters
*
value $3
Checks if a value is either
true or false#### Parameters
*
value $3
Checks if a function is a class constructor
#### Parameters
*
fn $3
Checks if a value is defined (opposite of isUndefined)
#### Parameters
*
value $3
Checks if a value is a DOM element, or if an element is a specific tag
#### Parameters
*
value
* tag $3
Checks if a value is:
*
undefined, null, false or 0
* an array or string with a length of 0
* an object without keys#### Parameters
*
value $3
Checks if a value is a function
#### Parameters
*
value $3
Checks if a value is an iterator (has a next method)
#### Parameters
*
value $3
Checks if a value is a number
#### Parameters
*
value $3
Checks if a value is a numeric
#### Parameters
*
value $3
Checks if a value is an object (and not an array or null)
#### Parameters
*
value $3
Checks if a value is a string
#### Parameters
*
value $3
Checks if a value is undefined (opposite of isDefined)
#### Parameters
*
value $3
Performs linear interpolation between two values
#### Parameters
*
a number current value
* b number target value
* n number progress (0-1)Returns number interpolated value
$3
Calculates relative luminance from an RGB array
#### Parameters
*
rgb Array<number> \[r, g, b] values (0-255)Returns number luminance value (0-255)
$3
Maps a value from one range to another
#### Parameters
*
value number original value
* inMin number lower bound of the current range
* inMax number upper bound of the current range
* outMin number lower bound of the target range
* outMax number upper bound of the target rangeReturns number new value mapped to the target range
$3
No operation
$3
Normalizes a value between two bounds
#### Parameters
*
value number value to normalize
* min number minimum boundary
* max number maximum boundaryReturns number normalized value (0-1)
$3
Creates a reactive proxy with subscribe method for state changes
#### Parameters
*
initial Object initial state object
* callback Function optional subscriber called on changes#### Examples
`javascript
const store = observable({count: 0});
const unsubscribe = store.subscribe((newState, oldState, key) => {
console.log(${key} changed from ${oldState.count} to ${newState.count});
});
store.count = 10;
unsubscribe();
`Returns Proxy proxied object with subscribe method
$3
Adds event listeners with optional delegation support
#### Parameters
*
events (string | Array<string>) event name(s), space-separated or array
* target (string | Element | Array<Element>) CSS selector (delegation) or element(s)
* callback Function event handler
* scope Element delegation scope (default: document) (optional, default document)#### Examples
`javascript
const off = on('click', '.button', handleClick);
const off = on('mouseenter mouseleave', el, handleHover);
`Returns Function cleanup function to remove listeners
$3
Extracts specified keys from an object, with support for dot notation and renaming
#### Parameters
*
object Object source object to extract from
* keys (string | Array<string>) key(s) to extract (supports dot notation and colon renaming)#### Examples
`javascript
only(obj, 'name'); // {name: 'John'}
only(obj, ['name', 'email']); // {name: 'John', email: 'john@example.com'}
only(obj, 'stats.age'); // {age: 45}
only(obj, 'stats.age:years'); // {years: 45}
only(obj, ['name', 'stats.age:years']); // {name: 'John', years: 45}
`Returns Object new object with only the specified keys
$3
Creates an event listener using on that fires only once
#### Parameters
*
type (string | Array<string>) event name(s)
* target (string | Element | Array<Element>) CSS selector or element(s)
* callback Function event handler
* scope Element delegation scope (default: document)Returns Function cleanup function to remove listener
$3
Appends ordinal suffix (st, nd, rd, th) to a number
#### Parameters
*
n number input numberReturns string number with ordinal suffix (e.g., '1st', '2nd', '3rd')
$3
Math constants PI, TWO\_PI, and HALF\_PI using Math.PI (3.141592653589793)
Type: number
$3
Creates a function that pipes input through multiple functions
#### Parameters
*
fns ...Function functions to chain#### Examples
`javascript
pipe(trim, lowercase, slugify)(' Hello World '); // 'hello-world'
`Returns Function composed function
$3
Creates a deferred promise with external resolve/reject
(consider using Promise.withResolvers() instead)
Returns Object object with promise, resolve, and reject properties
$3
Extracts a property value from each item in an array, or multiple properties using only
#### Parameters
*
array Array<Object> array of objects to pluck from
* key (string | Array<string>) property name or array of keys (supports dot notation and colon renaming via only)#### Examples
`javascript
pluck(users, 'name') // ['John', 'Jane']
pluck(users, ['name', 'email']) // [{name: 'John', email: '...'}, {name: 'Jane', email: '...'}]
pluck(users, ['name', 'stats.age']) // [{name: 'John', age: 45}, {name: 'Jane', age: 32}]
`Returns Array array of values when key is a string, or array of objects when key is an array
$3
Gets or sets a CSS custom property on an element
#### Parameters
*
el Element element
* name string property name (e.g., '--color')
* value string value to set (omit to get)Returns (string | undefined) property value when getting
$3
Multi-purpose random function:
* no arguments: returns random float 0-1
* array: returns random element from the array
* min: returns random float in range 0-min
* min and max: returns random float in range min-max
#### Parameters
*
min (number | Array) upper bound, or array to pick from
* max number upper bound when min is providedReturns (number | any) random number or random array element
$3
Gets the size and position of an element relative to the viewport using getBoundingClientRect
#### Parameters
*
el Element element to measureReturns DOMRect bounding client rect
$3
Fetch wrapper with common defaults and convenience methods
* defaults to sending
'Content-Type': 'application/json' headers
* defaults to resolving with the returned JSON response or rejecting with errors and status
* prefixes relative URLs with a preceeding slash
* converts the data argument to a JSON string or URL params for GET requests
* exposes request.headers for overriding the default headers
* exposes request.handler for overriding the default response handler passed to fetch(...).then(request.handler)
* creates request[method]() helpers#### Parameters
*
method string HTTP method
* url string request URL
* data Object request data (body or query params for GET)
* options Object additional fetch options (optional, default {})#### Examples
`javascript
request.get('https://api.example.com/users?limit=10');
request.get('/users', {limit: 10}); *
request.post('/login', {username, password});
request.headers['Authorization'] = Bearer ${token};
`Returns Promise promise resolving to JSON response
$3
Tracks resize events on an element using ResizeObserver
#### Parameters
*
el Element element to observe
* fn Function callback receiving ResizeObserverEntryReturns Function cleanup function to stop observing
$3
Rounds a value to the specified number of decimal places
#### Parameters
*
n number number to round
* precision number decimal places (default: 2) (optional, default 2)Returns number rounded value
$3
Wraps an async function with error handling
#### Parameters
*
fn Function async function to wrap
* handler Function error handlerReturns Function wrapped function that catches errors
$3
Awaits a promise and returns \[value, error] tuple for easier error handling
#### Parameters
*
promise Promise promise to await
* handler Function optional custom result handler#### Examples
`javascript
const [data, err] = await settled(fetchUser(id));
if (err) handleError(err);
`Returns Promise<Array> \[value, reason] tuple
$3
Shuffles an array in place, or returns a random sort comparator
#### Parameters
*
array Array array to shuffle (optional)Returns (Array | number) shuffled array, or random comparator if no array provided
$3
Converts a string to a URL-friendly slug
#### Parameters
*
str string string to convertReturns string lowercase, hyphenated slug
$3
Creates SVG elements using template literals
#### Parameters
*
strings TemplateStringsArray template literal strings
* vars ...any template literal values#### Examples
`javascript
const square = svg;const circle = svg
;
`Returns SVGElement parsed SVG element
$3
Creates a throttled function that only invokes once per wait period
#### Parameters
*
fn Function function to throttle
* wait number minimum time between calls in milliseconds#### Examples
`javascript
const throttledFn = throttle(onScroll, 100);
`Returns Function throttled function
$3
Converts a value to an array
#### Parameters
*
value any value to convert (NodeList, HTMLCollection, or any value)Returns Array array containing the value(s)
$3
Converts a value to boolean (handles string values like 'true', 'false', 'yes', 'no')
#### Parameters
*
value any value to convertReturns boolean boolean value
$3
Converts between JSON strings and objects
#### Parameters
*
value (string | Object) string to parse or object to stringify
* defaults Object default values to merge (when parsing) or extend (when stringifying)Returns (Object | string) parsed object or JSON string
$3
Converts radians to degrees
#### Parameters
*
radians number angle in radiansReturns number angle in degrees
$3
Converts degrees to radians
#### Parameters
*
degrees number angle in degreesReturns number angle in radians
$3
Formats a date or timestamp as a relative time string (e.g., "2 days ago", "in 3 hours")
#### Parameters
*
value (Date | number) Date object or timestamp in millisecondsReturns (string | null) relative time string, or null if value is invalid
$3
Converts a hex color string to an RGB array
#### Parameters
*
hex string hex color (with or without #)Returns (Array<number> | null) \[r, g, b] array (0-255) or null if invalid
$3
Traps focus within an element for keyboard navigation
#### Parameters
*
el Element container element
* callback Function optional function to filter/modify focusable elementsReturns Function cleanup function to restore previous focus
$3
Walks a DOM tree and calls callback for each node
#### Parameters
*
el Element root element to traverse
* callback Function function called for each node
* filter number NodeFilter constant (default: NodeFilter.SHOW\_ELEMENT)$3
Generates a unique base-16 string ID
#### Parameters
*
prefix string optional prefix (optional, default '')
* suffix string optional suffix (optional, default '')Returns string unique identifier
$3
Validates data against a set of rules
#### Parameters
*
data Object data to validate
* rules Object object of validator functions (return true or error string)#### Examples
`javascript
const data = {
email: 'hello@example.com',
password: 'password',
passwordConfirm: null
};const rules = {
email(value) {
return /.+\@.+\..+/.test(value) || 'Invalid email';
},
password(value) {
if (!value) return 'Required';
return value.length >= 8 || 'Must be at least 8 characters';
},
passwordConfirm(value, data) {
return value === data.password || 'Must match your password';
},
};
const errors = validate(data, rules);
`Returns (Object | null) errors object, or null if valid
$3
Returns a promise that resolves after a delay
#### Parameters
*
delay number time in millisecondsReturns Promise promise that resolves after delay
$3
Creates a Web Worker from a function or string
#### Parameters
*
code (Function | string) worker code as function or stringReturns Worker Web Worker instance
$3
Wraps an index around the given length using the modulo operator
#### Parameters
*
index number index to wrap
* n (number | Array) length or array#### Examples
`javascript
wrap(1, 3); // 1
wrap(3, 3); // 0
wrap(-1, 3); // 2
``Returns number wrapped index