A collection of convenient JavaScript utilities.
npm install @tmbr/utilsBreaking 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
- 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
- storage
- session
- svg
- template
- throttle
- toArray
- toBoolean
- toJSON
- toDegrees
- toRadians
- toRelativeTime
- toRGB
- trap
- traverse
- uid
- validate
- wait
- worker
- wrap
Gets, sets or removes an attribute from an element
elElement elementnamestring attribute namevalue(string | boolean) attribute value (falsy to remove)
Returns (string | undefined) attribute value when getting
Calculates the average from an array of numbers
Returns number average value
Binds methods to an instance, including class getters and setters (based on auto-bind)
selfObject target instancemethods(string | Array<string>) specific method name(s) to bind, or omit for all
class Example {
constructor() { bind(this); }
}Returns Object self for chaining
Calculates perceived brightness from an RGB array
Returns number brightness value (0-255)
Clamps a value between two bounds
valuenumber value to clampminnumber minimum boundary (default: 0) (optional, default0)maxnumber maximum boundary (default: 1) (optional, default1)
Returns number clamped value
Combines multiple functions into a single callback that calls all of them
fns...Function functions to combine
Returns Function combined function
Gets, sets, or deletes a cookie
namestring cookie namevalue(string | null) value to set, or null to deleteoptions(number | Date | Object) expiration days, Date, or cookie attributes
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
Gets x and y coordinates from a pointer event, optionally relative to a target element
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
args...(string | Object | Array) class names, objects, or arrayselElement optional element to modify
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
const debouncedFn = debounce(onInput, 300);Returns Function debounced function
Calculates the distance between two points
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
Gets or sets a value at a dot-notated path within a nested object
objectObject target objectpathstring dot-notated path (e.g., 'a.b.c')valueany value to set (omit to get)
dot(obj, 'user.name'); // get
dot(obj, 'user.name', 'Nik'); // setReturns any nested value when getting, or object when setting
Removes all children from an element (can be significantly faster than innerHTML)
elElement element to empty
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
Returns Array filled array
querySelectorAll wrapper with optional parent context
Returns Array<Element> array of matching elements
querySelector wrapper with optional parent context
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
patternstring format pattern (YYYY, MM, DD, HH, mm, ss, etc.)date(Date | string | number) date to format (default: now)
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
stringsTemplateStringsArray template literal stringsvars...any template literal values (strings, elements, or arrays)
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
Gets the index of an element among its siblings
elElement element to find index of
Returns number index within parent's children
Tracks enter and leave events on an element using IntersectionObserver
-
elElement element to observe -
optionsObject enter/leave callbacks, once boolean, and IntersectionObserver optionsoptions.enteroptions.leaveoptions.once(optional, defaultfalse)options.rest...any
const unobserve = io(el, {
enter: () => console.log('enter'),
leave: () => console.log('leave'),
});Returns Function cleanup function to stop observing
Checks if a value is an array using Array.isArray)
value
Checks if a value is either true or false
value
Checks if a function is a class constructor
fn
Checks if a value is defined (opposite of isUndefined)
value
Checks if a value is a DOM element, or if an element is a specific tag
valuetag
Checks if a value is:
undefined,null,falseor0- an array or string with a length of 0
- an object without keys
value
Checks if a value is a function
value
Checks if a value is an iterator (has a next method)
value
Checks if a value is a number
value
Checks if a value is a numeric
value
Checks if a value is an object (and not an array or null)
value
Checks if a value is a string
value
Checks if a value is undefined (opposite of isDefined)
value
Performs linear interpolation between two values
Returns number interpolated value
Calculates relative luminance from an RGB array
Returns number luminance value (0-255)
Maps a value from one range to another
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
No operation
Normalizes a value between two bounds
Returns number normalized value (0-1)
Creates a reactive proxy with subscribe method for state changes
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
Adds event listeners with optional delegation support
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)
const off = on('click', '.button', handleClick);
const off = on('mouseenter mouseleave', el, handleHover);Returns Function cleanup function to remove listeners
Extracts specified keys from an object, with support for dot notation and renaming
objectObject source object to extract fromkeys(string | Array<string>) key(s) to extract (supports dot notation and colon renaming)
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
Creates an event listener using on that fires only once
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
Appends ordinal suffix (st, nd, rd, th) to a number
nnumber input number
Returns string number with ordinal suffix (e.g., '1st', '2nd', '3rd')
Math constants PI, TWO_PI, and HALF_PI using Math.PI (3.141592653589793)
Type: number
Creates a function that pipes input through multiple functions
fns...Function functions to chain
pipe(trim, lowercase, slugify)(' Hello World '); // 'hello-world'Returns Function composed function
Creates a deferred promise with external resolve/reject (consider using Promise.withResolvers() instead)
Returns Object object with promise, resolve, and reject properties
Extracts a property value from each item in an array, or multiple properties using only
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)
pluck(users, 'name') // ['John', 'Jane']
pluck(users, 'stats.age') // [45, 39]
pluck(users, ['name', 'email']) // [{name: 'John', email: '...'}, {name: 'Jane', email: '...'}]
pluck(users, ['name', 'stats.age']) // [{name: 'John', age: 45}, {name: 'Jane', age: 39}]Returns Array array of values when key is a string, or array of objects when key is an array
Gets or sets a CSS custom property on an element
elElement elementnamestring property name (e.g., '--color')valuestring value to set (omit to get)
Returns (string | undefined) property value when getting
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
Returns (number | any) random number or random array element
Gets the size and position of an element relative to the viewport using getBoundingClientRect
elElement element to measure
Returns DOMRect bounding client rect
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
dataandstatus - 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
methodstring HTTP methodurlstring request URLdataObject request data (body or query params for GET)optionsObject additional fetch options (optional, default{})
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
Tracks resize events on an element using ResizeObserver
Returns Function cleanup function to stop observing
Rounds a value to the specified number of decimal places
Returns number rounded value
Wraps an async function with error handling
Returns Function wrapped function that catches errors
Awaits a promise and returns [value, error] tuple for easier error handling
const [ value, error ] = await settled(fetch(...));Returns Promise<Array> [value, error] array
Shuffles an array in place, or returns a random sort comparator
arrayArray array to shuffle (optional)
Returns (Array | number) shuffled array, or random comparator if no array provided
Converts a string to a URL-friendly slug
strstring string to convert
Returns string lowercase, hyphenated slug
localStorage wrapper with support for JSON and scalar values
storage.set('key', {a: 1});
storage.get('key'); // {a: 1}
storage.get('missing', 42); // 42
storage.remove('key');sessionStorage wrapper with support for JSON and scalar values
session.set('token', 'example');
session.get('token');Creates SVG elements using template literals
stringsTemplateStringsArray template literal stringsvars...any template literal values
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
Micro-templating with {{ }} interpolation and {# #} evaluation
const render = template('#example');
const html = render({name: 'Nik'});
const html = template('<p>{{ name }}</p>', {name: 'Nik'});Returns (Function | string) render function, or rendered string if data is provided
Creates a throttled function that only invokes once per wait period
const throttledFn = throttle(onScroll, 100);Returns Function throttled function
Converts a value to an array
valueany value to convert (NodeList, HTMLCollection, or any value)
Returns Array array containing the value(s)
Converts a value to boolean (handles string values like 'true', 'false', 'yes', 'no')
valueany value to convert
Returns boolean boolean value
Converts between JSON strings and objects
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
Converts radians to degrees
radiansnumber angle in radians
Returns number angle in degrees
Converts degrees to radians
degreesnumber angle in degrees
Returns number angle in radians
Formats a date or timestamp as a relative time string (e.g., "2 days ago", "in 3 hours")
Returns (string | null) relative time string, or null if value is invalid
Converts a hex color string to an RGB array
hexstring hex color (with or without #)
Returns (Array<number> | null) [r, g, b] array (0-255) or null if invalid
Traps focus within an element for keyboard navigation
elElement container elementcallbackFunction optional function to modify focusable elements (re-evaluated on each Tab press)
Returns Function cleanup function to restore previous focus
Walks a DOM tree and calls callback for each node
elElement root element to traversecallbackFunction function called for each nodefilternumber NodeFilter constant (default: NodeFilter.SHOW_ELEMENT)
Generates a unique base-16 string ID
prefixstring optional prefix (optional, default'')suffixstring optional suffix (optional, default'')
Returns string unique identifier
Validates data against a set of rules
dataObject data to validaterulesObject object of validator functions (return true or error string)
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
Returns a promise that resolves after a delay
delaynumber time in milliseconds
Returns Promise promise that resolves after delay
Creates a Web Worker from a function or string
Returns Worker Web Worker instance
Wraps an index around the given length using the modulo operator
wrap(1, 3); // 1
wrap(3, 3); // 0
wrap(-1, 3); // 2Returns number wrapped index