A collection of convenient JavaScript utilities.
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 change -
parse
is nowtoJSON
-
setProperty
is nowprop
and no longer falls back to the root html element if value is ommitted -
createWorker
is nowworker
- attr
- average
- bind
- brightness
- clamp
- combine
- cookie
- coords
- cx
- debounce
- distance
- dot
- empty
- fill
- findAll
- findOne
- focusables
- html
- indexOf
- io
- isArray
- isBoolean
- isClass
- isDefined
- isElement
- isEmpty
- isFunction
- isNumber
- isNumeric
- isObject
- isString
- isUndefined
- lerp
- luminance
- map
- noop
- normalize
- observable
- on
- once
- PI
- pipe
- pledge
- prop
- random
- rect
- request
- ro
- round
- shuffle
- slug
- svg
- throttle
- toArray
- toBoolean
- toJSON
- toDegrees
- toRadians
- toRGB
- trap
- traverse
- uid
- validate
- wait
- worker
- wrap
Gets, sets or removes an attribute from an element
-
el
element -
name
attribute name -
value
attribute value
Returns any value (if getting) or undefined
Calculates the average from an array of numbers
-
values
Returns any number
Binds functions to a context or instance, including class getters and setters (based on auto-bind)
-
self
target instance to bethis
-
methods
optional method(s) to bind as a string or array of names
Returns any self for chaining
Calculates brightness from an rgb array
-
rgb
array of red, green and blue values in the range 0-255
Returns any brightness value between 0-255
Clamps a value between two bounds
-
value
value to clamp -
min
minimum boundary (0) (optional, default0
) -
max
maximum boundary (1) (optional, default1
)
Returns any clamped value
Combines functions into a single callback
-
fns
...any individual function arguments
Gets or sets a cookie
-
name
name of the cookie -
value
value to set (usenull
to delete) -
options
optional expiration days, Date instance or object of attributes
cookie('greeting', 'Hello');
cookie('greeting'); // Hello
cookie('greeting', null);
cookie('example', 'Expire in 30 days', 30);
cookie('example', 'Expire on this date', new Date(...));
cookie('example', 'Custom cookie attributes', {SameSite: 'strict'});
Gets the x and y coordinates of a pointer event, optionally relative to a target element
-
event
event object -
target
optional target element
Returns any object with x and y properties
Conditionally toggles classes on an element or generates a string of classes, similar to classnames)
-
args
...any
Creates a debounced version of a function which postpones execution until specified wait time since the function was last invoked
-
fn
function to debounce -
wait
time in milliseconds
Calculates the distance between two points
-
x1
mixed x coordinate or object with x and y properties -
y1
mixed y coordinate or object with x and y properties -
x2
number optional, x coordinate of the second point -
y2
number optional, y coordinate of the second point
Returns number distance
Gets or sets a dot-notated path within a nested object
-
object
target object -
path
string path -
value
optional value to set
Returns any target object if setting (for chaining) or value if getting
Efficiently clears the DOM tree from the target element by removing all children,
which is can be significantly faster than using innerHTML
-
el
const div = document.querySelector('.example');
empty(div).append(fragment);
Fills an array of a specified length using a callback or value
-
n
length of array -
value
single value or callback that should return the value for the given index
Returns array
querySelectorAll
wrapper with an optional parent context that always converts the resulting
NodeList to an array
-
selector
-
parent
querySelector
wrapper with an optional parent context
-
selector
-
parent
Exports an array of CSS selectors for elements that can receive focus (based on focusable-selectors)
Creates DOM elements using template literals (based on facon))
-
strings
-
vars
...any
const img = html`<img src="https://placehold.co/600x400" alt="">`;
const div = html`<div>${img}</div>`;
Gets the child index of the provided element
-
el
-
HTMLElement
Returns number
Tracks enter and leave events on the provided element
-
el
element to observe -
options
Object object with optionalenter
andleave
callbacks,once
boolean and...rest
args passed to the underlying IntersectionObserver-
options.enter
-
options.leave
-
options.once
(optional, defaultfalse
) -
options.rest
...any
-
Returns any unobserve cleanup function
Checks if a value is an array using Array.isArray)
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
-
value
-
tag
Checks if a value is:
-
undefined
,null
,false
or0
- 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 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 luminance from an rgb array
-
rgb
array of red, green and blue values in the range 0-255
Returns any luminance value between 0-255
Maps a value from one range to another
-
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 range
Returns number new value mapped to the target range
No operation
Normalizes a value between two bounds
Returns number normalized value
Creates a Proxy
instance with a subscribe
method that can be used to respond to state changes
-
initial
initial state object -
callback
optional subscribed callback function
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 any proxied object
Adds an event listener to a target element or array of elements, or creates a delegate listener for the target selector string
-
events
-
target
target element, array of elements or a CSS selector for event delegation -
callback
callback function -
scope
optional parent scope (optional, defaultdocument
) -
event
name of event, or multiple events as either an array or space-separated spring
Returns any function to remove all listeners
Wraps on to create an event listener that will only fire once
-
type
-
target
-
callback
-
scope
Exports PI
, TWO_PI
and HALF_PI
using Math.PI (3.141592653589793)
Creates a function that chains multiple function calls by passing the result from one to the next
-
fns
...any individual function arguments
Returns function
Creates an object with a reference to a Promise that can be resolved or rejected externally
Returns any object with a resolve
function, a reject
function and the promise
instance
Gets a sets a CSS custom property on an element
-
el
element -
name
property name -
value
property value
Returns any value (if getting) or undefined
Multi-purpose random function:
- if no arguments are passed, returns random float 0-1 from Math.random()
- if an array is passed, returns a random element from the array
- if min is passed, returns a random float in the range 0-min
- if min and max are passed, returns a random float in the range min-max
-
min
-
max
Returns any random number or random element from array
Gets the size and position of an element relative to the viewport using getBoundingClientRect
-
el
-
HTMLElement
fetch wrapper with some conveniences:
- defaults to sending
'Content-Type': 'application/json'
headers - defaults to resolving with the returned JSON response or rejecting with
errors
andstatus
- 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 tofetch(...).then(request.handler)
- creates
request[method]()
-
method
HTTP method (if callingrequest()
directly) -
url
URL of the resource you want to fetch -
data
request data to be sent -
options
fetch options (optional, default{}
)
request.get('https://api.example.com/users?limit=10');
request.get('users', {limit: 10});
request.headers['Authorization'] = `Bearer ${token}`;
request.post('/login', {username, password});
Tracks resize events on the provided element
-
el
element to observe -
fn
function to call when resized, receives a ResizeObserverEntry
Returns any unobserve cleanup function
Rounds a value to the specificed number of decimal places
-
n
number to round -
precision
decimal places (optional, default2
)
Returns any rounded value
Shuffles an array
-
array
optional array to be shuffled in place
Returns any shuffled array or a random number to be used as a sort compare
Creates a URL-friendly slug version of a string
-
str
Creates SVG elements using template literals
-
strings
-
vars
...any
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>`;
Creates a throttled version of a function which will only be called once per the specified wait time
-
fn
function to throttle -
wait
time in milliseconds
Converts a value to an array
-
value
Converts a value to true
or false
-
value
Converts a string to JSON with optional defaults
-
string
-
defaults
Converts radians to degrees
-
radians
number
Returns number degrees
Converts degrees to radians
-
degrees
number
Returns number radians
Converts a hexidecimal string to an rgb array
-
hex
string original RRGGBB hex color, with or without the preceeding #
Returns array r, g and b values in the range 0-255
Traps focus on the given element with an optional callback to modify the array of focusable elements
-
el
-
callback
Returns any function to untrap
Recursively passes a DOM element's children to the provided callback
-
el
root element to travese -
callback
function to be called for each child element -
filter
filter passed to createTreeWalker (defaults toNodeFilter.SHOW_ELEMENT
)
Generates a unique base 16 string with an optional prefix or suffix.
-
prefix
(optional, default''
) -
suffix
(optional, default''
)
Validates data against a set of rules
-
data
-
rules
const data = {
email: 'hello@example.com',
password: 'password',
confirm: 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';
},
confirm(value, data) {
if (!value) return 'Required';
return value === data.password || 'Must match your password';
},
};
const errors = validate(data, rules);
Returns any errors object or null if all keys passed validation
Returns a Promise that resolves after the specified delay in milliseconds
-
delay
Creates a Web Worker instance with the provided function
or string
-
code
Wraps an index around the given length using the modulo operator.
wrap(1, 3); // 1
wrap(3, 3); // 0
wrap(-1, 3); // 2
Returns number looped index