@tmbr/utils
v2.5.0
Published
A collection of convenient JavaScript utilities.
Downloads
144
Readme
utils
A collection of convenient JavaScript utilities.
npm install @tmbr/utils
Upgrading
Breaking changes introduced in version 2.0.0
:
request
headers param is now fetch options (allows cancellation via AbortController)io
function signature changeparse
is nowtoJSON
setProperty
is nowprop
and no longer falls back to the root html element if value is ommittedcreateWorker
is nowworker
Documentation
Table of Contents
- attr
- average
- bind
- brightness
- clamp
- combine
- cookie
- coords
- cx
- debounce
- distance
- dot
- 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
- wait
- worker
- wrap
attr
Gets, sets or removes an attribute from an element
Parameters
el
elementname
attribute namevalue
attribute value
Returns any value (if getting) or undefined
average
Calculates the average from an array of numbers
Parameters
values
Returns any number
bind
Binds functions to a context or instance, including class getters and setters (based on auto-bind)
Parameters
self
target instance to bethis
methods
optional method(s) to bind as a string or array of names
Returns any self for chaining
brightness
Calculates brightness from an rgb array
Parameters
rgb
array of red, green and blue values in the range 0-255
Returns any brightness value between 0-255
clamp
Clamps a value between two bounds
Parameters
value
value to clampmin
minimum boundary (0) (optional, default0
)max
maximum boundary (1) (optional, default1
)
Returns any clamped value
combine
Combines functions into a single callback
Parameters
fns
...any individual function arguments
cookie
Gets or sets a cookie
Parameters
name
name of the cookievalue
value to set (usenull
to delete)options
optional expiration days, Date instance or object of attributes
Examples
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'});
coords
Gets the x and y coordinates of a pointer event, optionally relative to a target element
Parameters
event
event objecttarget
optional target element
Returns any object with x and y properties
cx
Conditionally toggles classes on an element or generates a string of classes, similar to classnames)
Parameters
args
...any
debounce
Creates a debounced version of a function which postpones execution until specified wait time since the function was last invoked
Parameters
fn
function to debouncewait
time in milliseconds
distance
Calculates the distance between two points
Parameters
x1
mixed x coordinate or object with x and y propertiesy1
mixed y coordinate or object with x and y propertiesx2
number optional, x coordinate of the second pointy2
number optional, y coordinate of the second point
Returns number distance
dot
Gets or sets a dot-notated path within a nested object
Parameters
object
target objectpath
string pathvalue
optional value to set
Returns any target object if setting (for chaining) or value if getting
fill
Fills an array of a specified length using a callback or value
Parameters
n
length of arrayvalue
single value or callback that should return the value for the given index
Returns array
findAll
querySelectorAll
wrapper with an optional parent context that always converts the resulting
NodeList to an array
Parameters
selector
parent
findOne
querySelector
wrapper with an optional parent context
Parameters
selector
parent
focusables
Exports an array of CSS selectors for elements that can receive focus (based on focusable-selectors)
html
Creates DOM elements using template literals (based on facon))
Parameters
strings
vars
...any
Examples
const img = html`<img src="https://placehold.co/600x400" alt="">`;
const div = html`<div>${img}</div>`;
indexOf
Gets the child index of the provided element
Parameters
el
HTMLElement
Returns number
io
Tracks enter and leave events on the provided element
Parameters
el
element to observeoptions
Object object with optionalenter
andleave
callbacks,once
boolean and...rest
args passed to the underlying IntersectionObserveroptions.enter
options.leave
options.once
(optional, defaultfalse
)options.rest
...any
Returns any unobserve cleanup function
isArray
Checks if a value is an array using Array.isArray)
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
value
tag
isEmpty
Checks if a value is:
undefined
,null
,false
or0
- 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
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 luminance from an rgb array
Parameters
rgb
array of red, green and blue values in the range 0-255
Returns any luminance value between 0-255
map
Maps a value from one range to another
Parameters
value
number original valueinMin
number lower bound of the current rangeinMax
number upper bound of the current rangeoutMin
number lower bound of the target rangeoutMax
number 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
observable
Creates a Proxy
instance with a subscribe
method that can be used to respond to state changes
Parameters
initial
initial state object
Examples
const store = observable({count: 0});
const unsubscribe = store.subscribe((newState, oldState) => {
console.log(`count changed from ${oldState.count} to ${newState.count}`);
});
store.count = 10;
unsubscribe();
Returns any proxied object
on
Adds an event listener to a target element or array of elements, or creates a delegate listener for the target selector string
Parameters
type
target
target element, array of elements or a CSS selector for event delegationcallback
callback functionscope
optional parent scope (optional, defaultdocument
)event
name of event (or multiple events separated by spaces)
Returns any function to remove all listeners
once
Wraps on to create an event listener that will only fire once
Parameters
type
target
callback
scope
PI
Exports PI
, TWO_PI
and HALF_PI
using Math.PI (3.141592653589793)
pipe
Creates a function that chains multiple function calls by passing the result from one to the next
Parameters
fns
...any individual function arguments
Returns function
pledge
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
prop
Gets a sets a CSS custom property on an element
Parameters
el
elementname
property namevalue
property value
Returns any value (if getting) or undefined
random
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
Parameters
min
max
Returns any random number or random element from array
rect
Gets the size and position of an element relative to the viewport using getBoundingClientRect
Parameters
el
HTMLElement
request
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]()
Parameters
method
HTTP method (if callingrequest()
directly)url
URL of the resource you want to fetchdata
request data to be sentoptions
fetch options (optional, default{}
)
Examples
request.get('https://api.example.com/users?limit=10');
request.get('users', {limit: 10});
request.headers['Authorization'] = `Bearer ${token}`;
request.post('/login', {username, password});
ro
Tracks resize events on the provided element
Parameters
el
element to observefn
function to call when resized, receives a ResizeObserverEntry
Returns any unobserve cleanup function
round
Rounds a value to the specificed number of decimal places
Parameters
n
number to roundprecision
decimal places (optional, default2
)
Returns any rounded value
shuffle
Shuffles an array
Parameters
array
optional array to be shuffled in place
Returns any shuffled array or a random number to be used as a sort compare
slug
Creates a URL-friendly slug version of a string
Parameters
str
svg
Creates SVG elements using template literals
Parameters
strings
vars
...any
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>`;
throttle
Creates a throttled version of a function which will only be called once per the specified wait time
Parameters
fn
function to throttlewait
time in milliseconds
toArray
Converts a value to an array
Parameters
value
toBoolean
Converts a value to true
or false
Parameters
value
toJSON
Converts a string to JSON with optional defaults
Parameters
string
defaults
toDegrees
Converts radians to degrees
Parameters
radians
number
Returns number degrees
toRadians
Converts degrees to radians
Parameters
degrees
number
Returns number radians
toRGB
Converts a hexidecimal string to an rgb array
Parameters
hex
string original RRGGBB hex color, with or without the preceeding #
Returns array r, g and b values in the range 0-255
trap
Traps focus on the given element with an optional callback to modify the array of focusable elements
Parameters
node
callback
Returns any function to untrap
traverse
Recursively passes a DOM element's children to the provided callback
Parameters
node
root element to travesecallback
function to be called for each child elementfilter
filter passed to createTreeWalker (defaults toNodeFilter.SHOW_ELEMENT
)
uid
Generates a unique base 16 string with an optional prefix or suffix.
Parameters
prefix
(optional, default''
)suffix
(optional, default''
)
wait
Returns a Promise that resolves after the specified delay in milliseconds
Parameters
delay
worker
Creates a Web Worker instance with the provided function
or string
Parameters
code
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); // 2
Returns number looped index