@tmbr/utils
v2.13.1
Published
A collection of convenient JavaScript utilities.
Readme
utils
A collection of convenient JavaScript utilities.
npm install @tmbr/utilsUpgrading
Breaking changes introduced in version 2.0.0:
requestheaders param is now fetch options (allows cancellation via AbortController)iofunction signature changeparseis nowtoJSONsetPropertyis nowpropand no longer falls back to the root html element if value is ommittedcreateWorkeris nowworker
Documentation
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
attr
Gets, sets or removes an attribute from an element
Parameters
elElement elementnamestring attribute namevalue(string | boolean) attribute value (falsy to remove)
Returns (string | undefined) attribute value when getting
average
Calculates the average from an array of numbers
Parameters
Returns number average value
bind
Binds methods to an instance, including class getters and setters (based on auto-bind)
Parameters
selfObject target instancemethods(string | Array<string>) specific method name(s) to bind, or omit for all
Examples
class Example {
constructor() { bind(this); }
}Returns Object self for chaining
brightness
Calculates perceived brightness from an RGB array
Parameters
Returns number brightness value (0-255)
clamp
Clamps a value between two bounds
Parameters
valuenumber value to clampminnumber minimum boundary (default: 0) (optional, default0)maxnumber maximum boundary (default: 1) (optional, default1)
Returns number clamped value
combine
Combines multiple functions into a single callback that calls all of them
Parameters
fns...Function functions to combine
Returns Function combined function
cookie
Gets, sets, or deletes a cookie
Parameters
namestring cookie namevalue(string | null) value to set, or null to deleteoptions(number | Date | Object) expiration days, Date, or cookie attributes
Examples
cookie('name', 'value'); // set
cookie('name'); // get
cookie('name', null); // delete
cookie('name', 'value', 30); // expires in 30 daysReturns (string | undefined) cookie value when getting
coords
Gets x and y coordinates from a pointer event, optionally relative to a target element
Parameters
Returns Object object with x, y (and px, py percentages if target provided)
cx
Conditionally toggles classes on an element or generates a string of classes, similar to classnames
Parameters
args...(string | Object | Array) class names, objects, or arrayselElement optional element to modify
Examples
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
debounce
Creates a debounced function that delays invocation until after wait ms have elapsed since the last call
Parameters
Examples
const debouncedFn = debounce(onInput, 300);Returns Function debounced function
distance
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 propertiesx2number x coordinate of the second point (when using coordinates)y2number y coordinate of the second point (when using coordinates)
Returns number distance
dot
Gets or sets a value at a dot-notated path within a nested object
Parameters
objectObject target objectpathstring dot-notated path (e.g., 'a.b.c')valueany value to set (omit to get)
Examples
dot(obj, 'user.name'); // get
dot(obj, 'user.name', 'Nik'); // setReturns any nested value when getting, or object when setting
empty
Removes all children from an element (can be significantly faster than innerHTML)
Parameters
elElement element to empty
Examples
const div = document.querySelector('.example');
empty(div).append(fragment);Returns Element the emptied element for chaining
fill
Creates an array of specified length filled with values
Parameters
Returns Array filled array
findAll
querySelectorAll wrapper with optional parent context
Parameters
Returns Array<Element> array of matching elements
findOne
querySelector wrapper with optional parent context
Parameters
Returns (Element | null) matching element or null
focusables
Array of CSS selectors for focusable elements based on focusable-selectors
format
Formats a date according to a pattern string
Parameters
patternstring format pattern (YYYY, MM, DD, HH, mm, ss, etc.)date(Date | string | number) date to format (default: now)
Examples
format('MMMM Do, YYYY'); // 'January 1st, 2024'
format('YYYY-MM-DD', someDate); // '2024-01-01'Returns string formatted date string
html
Creates DOM elements using template literals, inspired by facon
Parameters
stringsTemplateStringsArray template literal stringsvars...any template literal values (strings, elements, or arrays)
Examples
const img = html`<img src="/image.jpg" alt="">`;
const list = html`<ul>${items.map(i => html`<li>${i}</li>`)}</ul>`;Returns (Element | DocumentFragment) single element or fragment if multiple root nodes
indexOf
Gets the index of an element among its siblings
Parameters
elElement element to find index of
Returns number index within parent's children
io
Tracks enter and leave events on an element using IntersectionObserver
Parameters
elElement element to observeoptionsObject enter/leave callbacks, once boolean, and IntersectionObserver optionsoptions.enteroptions.leaveoptions.once(optional, defaultfalse)options.rest...any
Examples
const unobserve = io(el, {
enter: () => console.log('enter'),
leave: () => console.log('leave'),
});Returns Function cleanup function to stop observing
isArray
Checks if a value is an array using Array.isArray)
Parameters
value
isBoolean
Checks if a value is either true or false
Parameters
value
isClass
Checks if a function is a class constructor
Parameters
fn
isDefined
Checks if a value is defined (opposite of isUndefined)
Parameters
value
isElement
Checks if a value is a DOM element, or if an element is a specific tag
Parameters
valuetag
isEmpty
Checks if a value is:
undefined,null,falseor0- an array or string with a length of 0
- an object without keys
Parameters
value
isFunction
Checks if a value is a function
Parameters
value
isIterator
Checks if a value is an iterator (has a next method)
Parameters
value
isNumber
Checks if a value is a number
Parameters
value
isNumeric
Checks if a value is a numeric
Parameters
value
isObject
Checks if a value is an object (and not an array or null)
Parameters
value
isString
Checks if a value is a string
Parameters
value
isUndefined
Checks if a value is undefined (opposite of isDefined)
Parameters
value
lerp
Performs linear interpolation between two values
Parameters
Returns number interpolated value
luminance
Calculates relative luminance from an RGB array
Parameters
Returns number luminance value (0-255)
map
Maps a value from one range to another
Parameters
valuenumber original valueinMinnumber lower bound of the current rangeinMaxnumber upper bound of the current rangeoutMinnumber lower bound of the target rangeoutMaxnumber upper bound of the target range
Returns number new value mapped to the target range
noop
No operation
normalize
Normalizes a value between two bounds
Parameters
Returns number normalized value (0-1)
observable
Creates a reactive proxy with subscribe method for state changes
Parameters
Examples
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
on
Adds event listeners with optional delegation support
Parameters
events(string | Array<string>) event name(s), space-separated or arraytarget(string | Element | Array<Element>) CSS selector (delegation) or element(s)callbackFunction event handlerscopeElement delegation scope (default: document) (optional, defaultdocument)
Examples
const off = on('click', '.button', handleClick);
const off = on('mouseenter mouseleave', el, handleHover);Returns Function cleanup function to remove listeners
only
Extracts specified keys from an object, with support for dot notation and renaming
Parameters
objectObject source object to extract fromkeys(string | Array<string>) key(s) to extract (supports dot notation and colon renaming)
Examples
only(obj, 'name'); // {name: 'John'}
only(obj, ['name', 'email']); // {name: 'John', email: '[email protected]'}
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
once
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)callbackFunction event handlerscopeElement delegation scope (default: document)
Returns Function cleanup function to remove listener
ordinal
Appends ordinal suffix (st, nd, rd, th) to a number
Parameters
nnumber input number
Returns string number with ordinal suffix (e.g., '1st', '2nd', '3rd')
PI
Math constants PI, TWO_PI, and HALF_PI using Math.PI (3.141592653589793)
Type: number
pipe
Creates a function that pipes input through multiple functions
Parameters
fns...Function functions to chain
Examples
pipe(trim, lowercase, slugify)(' Hello World '); // 'hello-world'Returns Function composed function
pledge
Creates a deferred promise with external resolve/reject (consider using Promise.withResolvers() instead)
Returns Object object with promise, resolve, and reject properties
pluck
Extracts a property value from each item in an array, or multiple properties using only
Parameters
arrayArray<Object> array of objects to pluck fromkey(string | Array<string>) property name or array of keys (supports dot notation and colon renaming via only)
Examples
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
prop
Gets or sets a CSS custom property on an element
Parameters
elElement elementnamestring property name (e.g., '--color')valuestring value to set (omit to get)
Returns (string | undefined) property value when getting
random
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
Returns (number | any) random number or random array element
rect
Gets the size and position of an element relative to the viewport using getBoundingClientRect
Parameters
elElement element to measure
Returns DOMRect bounding client rect
request
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
errorsandstatus - prefixes relative URLs with a preceeding slash
- converts the data argument to a JSON string or URL params for
GETrequests - exposes
request.headersfor overriding the default headers - exposes
request.handlerfor overriding the default response handler passed tofetch(...).then(request.handler) - creates
request[method]()helpers
Parameters
methodstring HTTP methodurlstring request URLdataObject request data (body or query params for GET)optionsObject additional fetch options (optional, default{})
Examples
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
ro
Tracks resize events on an element using ResizeObserver
Parameters
Returns Function cleanup function to stop observing
round
Rounds a value to the specified number of decimal places
Parameters
Returns number rounded value
safe
Wraps an async function with error handling
Parameters
Returns Function wrapped function that catches errors
settled
Awaits a promise and returns [value, error] tuple for easier error handling
Parameters
Examples
const [data, err] = await settled(fetchUser(id));
if (err) handleError(err);Returns Promise<Array> [value, reason] tuple
shuffle
Shuffles an array in place, or returns a random sort comparator
Parameters
arrayArray array to shuffle (optional)
Returns (Array | number) shuffled array, or random comparator if no array provided
slug
Converts a string to a URL-friendly slug
Parameters
strstring string to convert
Returns string lowercase, hyphenated slug
svg
Creates SVG elements using template literals
Parameters
stringsTemplateStringsArray template literal stringsvars...any template literal values
Examples
const square = svg`
<svg viewBox="0 0 100 100">
<rect fill="#FF0000" width="100" height="100" />
</svg>`;
const circle = svg`
<svg viewBox="0 0 100 100">
<circle fill="#FF0000" r="50" cx="50" cy="50" />
</svg>`;Returns SVGElement parsed SVG element
throttle
Creates a throttled function that only invokes once per wait period
Parameters
Examples
const throttledFn = throttle(onScroll, 100);Returns Function throttled function
toArray
Converts a value to an array
Parameters
valueany value to convert (NodeList, HTMLCollection, or any value)
Returns Array array containing the value(s)
toBoolean
Converts a value to boolean (handles string values like 'true', 'false', 'yes', 'no')
Parameters
valueany value to convert
Returns boolean boolean value
toJSON
Converts between JSON strings and objects
Parameters
value(string | Object) string to parse or object to stringifydefaultsObject default values to merge (when parsing) or extend (when stringifying)
Returns (Object | string) parsed object or JSON string
toDegrees
Converts radians to degrees
Parameters
radiansnumber angle in radians
Returns number angle in degrees
toRadians
Converts degrees to radians
Parameters
degreesnumber angle in degrees
Returns number angle in radians
toRelativeTime
Formats a date or timestamp as a relative time string (e.g., "2 days ago", "in 3 hours")
Parameters
Returns (string | null) relative time string, or null if value is invalid
toRGB
Converts a hex color string to an RGB array
Parameters
hexstring hex color (with or without #)
Returns (Array<number> | null) [r, g, b] array (0-255) or null if invalid
trap
Traps focus within an element for keyboard navigation
Parameters
Returns Function cleanup function to restore previous focus
traverse
Walks a DOM tree and calls callback for each node
Parameters
elElement root element to traversecallbackFunction function called for each nodefilternumber NodeFilter constant (default: NodeFilter.SHOW_ELEMENT)
uid
Generates a unique base-16 string ID
Parameters
prefixstring optional prefix (optional, default'')suffixstring optional suffix (optional, default'')
Returns string unique identifier
validate
Validates data against a set of rules
Parameters
dataObject data to validaterulesObject object of validator functions (return true or error string)
Examples
const data = {
email: '[email protected]',
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
wait
Returns a promise that resolves after a delay
Parameters
delaynumber time in milliseconds
Returns Promise promise that resolves after delay
worker
Creates a Web Worker from a function or string
Parameters
Returns Worker Web Worker instance
wrap
Wraps an index around the given length using the modulo operator
Parameters
Examples
wrap(1, 3); // 1
wrap(3, 3); // 0
wrap(-1, 3); // 2Returns number wrapped index
