@tmbr/utils

2.7.0 • Public • Published

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 change
  • parse is now toJSON
  • setProperty is now prop and no longer falls back to the root html element if value is ommitted
  • createWorker is now worker

Documentation

Table of Contents

attr

Gets, sets or removes an attribute from an element

Parameters

  • el element
  • name attribute name
  • value 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 be this
  • 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 clamp
  • min minimum boundary (0) (optional, default 0)
  • max maximum boundary (1) (optional, default 1)

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 cookie
  • value value to set (use null 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 object
  • target 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 debounce
  • wait time in milliseconds

distance

Calculates the distance between two points

Parameters

  • 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

dot

Gets or sets a dot-notated path within a nested object

Parameters

  • object target object
  • path string path
  • value optional value to set

Returns any target object if setting (for chaining) or value if getting

empty

Efficiently clears the DOM tree from the target element by removing all children, which is can be significantly faster than using innerHTML

Parameters

  • el

Examples

const div = document.querySelector('.example');
empty(div).append(fragment);

fill

Fills an array of a specified length using a callback or value

Parameters

  • n length of array
  • value 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 observe

  • options Object object with optional enter and leave callbacks, once boolean and ...rest args passed to the underlying IntersectionObserver

    • options.enter
    • options.leave
    • options.once (optional, default false)
    • 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 or 0
  • 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 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

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
  • callback optional subscribed callback function

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 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

  • events
  • target target element, array of elements or a CSS selector for event delegation
  • callback callback function
  • scope optional parent scope (optional, default document)
  • event name of event, or multiple events as either an array or space-separated spring

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 element
  • name property name
  • value 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 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]()

Parameters

  • method HTTP method (if calling request() directly)
  • url URL of the resource you want to fetch
  • data request data to be sent
  • options 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

Returns any unobserve cleanup function

round

Rounds a value to the specificed number of decimal places

Parameters

  • n number to round
  • precision decimal places (optional, default 2)

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 throttle
  • wait 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

Returns number degrees

toRadians

Converts degrees to radians

Parameters

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

  • el
  • callback

Returns any function to untrap

traverse

Recursively passes a DOM element's children to the provided callback

Parameters

  • el root element to travese
  • callback function to be called for each child element
  • filter filter passed to createTreeWalker (defaults to NodeFilter.SHOW_ELEMENT)

uid

Generates a unique base 16 string with an optional prefix or suffix.

Parameters

  • prefix (optional, default '')
  • suffix (optional, default '')

validate

Validates data against a set of rules

Parameters

  • data
  • rules

Examples

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

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

Readme

Keywords

none

Package Sidebar

Install

npm i @tmbr/utils

Weekly Downloads

55

Version

2.7.0

License

none

Unpacked Size

56 kB

Total Files

70

Last publish

Collaborators

  • nikrowell