npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@tmbr/utils

v2.13.1

Published

A collection of convenient JavaScript utilities.

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

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

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

  • value number value to clamp
  • min number minimum boundary (default: 0) (optional, default 0)
  • max number maximum boundary (default: 1) (optional, default 1)

Returns number clamped value

combine

Combines multiple functions into a single callback that calls all of them

Parameters

Returns Function combined function

cookie

Gets, sets, or deletes a cookie

Parameters

  • name string cookie name
  • value (string | null) value to set, or null to delete
  • options (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 days

Returns (string | undefined) cookie value when getting

coords

Gets x and y coordinates from a pointer event, optionally relative to a target element

Parameters

  • event Event mouse or touch event
  • target Element optional element for relative coordinates

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

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 properties
  • y1 (number | Object) y coordinate or object with x and y properties
  • x2 number x coordinate of the second point (when using coordinates)
  • y2 number 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

  • object Object target object
  • path string dot-notated path (e.g., 'a.b.c')
  • value any value to set (omit to get)

Examples

dot(obj, 'user.name');        // get
dot(obj, 'user.name', 'Nik'); // set

Returns any nested value when getting, or object when setting

empty

Removes all children from an element (can be significantly faster than innerHTML)

Parameters

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

  • n number array length
  • value (any | Function) fill value, or function receiving index

Returns Array filled array

findAll

querySelectorAll wrapper with optional parent context

Parameters

  • selector string CSS selector
  • parent Element parent element (default: document)

Returns Array<Element> array of matching elements

findOne

querySelector wrapper with optional parent context

Parameters

  • selector string CSS selector
  • parent Element parent element (default: document)

Returns (Element | null) matching element or null

focusables

Array of CSS selectors for focusable elements based on focusable-selectors

Type: Array<string>

format

Formats a date according to a pattern string

Parameters

  • pattern string 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

  • strings TemplateStringsArray template literal strings
  • vars ...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

  • el Element element to find index of

Returns number index within parent's children

io

Tracks enter and leave events on an element using IntersectionObserver

Parameters

  • el Element element to observe

  • options Object enter/leave callbacks, once boolean, and IntersectionObserver options

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

  • 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

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

  • 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 (0-1)

observable

Creates a reactive proxy with subscribe method for state changes

Parameters

  • initial Object initial state object
  • callback Function optional subscriber called on changes

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

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

  • object Object source object to extract from
  • keys (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

Returns Function cleanup function to remove listener

ordinal

Appends ordinal suffix (st, nd, rd, th) to a number

Parameters

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

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

  • array Array<Object> array of objects to pluck from
  • key (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

  • el Element element
  • name string property name (e.g., '--color')
  • value string 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

  • min (number | Array) upper bound, or array to pick from
  • max number upper bound when min is provided

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

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 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]() helpers

Parameters

  • method string HTTP method
  • url string request URL
  • data Object request data (body or query params for GET)
  • options Object 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

  • el Element element to observe
  • fn Function callback receiving ResizeObserverEntry

Returns Function cleanup function to stop observing

round

Rounds a value to the specified number of decimal places

Parameters

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

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

  • promise Promise promise to await
  • handler Function optional custom result handler

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

  • array Array 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

Returns string lowercase, hyphenated slug

svg

Creates SVG elements using template literals

Parameters

  • strings TemplateStringsArray template literal strings
  • vars ...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

  • fn Function function to throttle
  • wait number minimum time between calls in milliseconds

Examples

const throttledFn = throttle(onScroll, 100);

Returns Function throttled function

toArray

Converts a value to an array

Parameters

  • value any 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

  • value any value to convert

Returns boolean boolean value

toJSON

Converts between JSON strings and objects

Parameters

  • value (string | Object) string to parse or object to stringify
  • defaults Object default values to merge (when parsing) or extend (when stringifying)

Returns (Object | string) parsed object or JSON string

toDegrees

Converts radians to degrees

Parameters

  • radians number angle in radians

Returns number angle in degrees

toRadians

Converts degrees to radians

Parameters

  • degrees number 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

  • value (Date | number) Date object or timestamp in milliseconds

Returns (string | null) relative time string, or null if value is invalid

toRGB

Converts a hex color string to an RGB array

Parameters

  • hex string 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

  • el Element container element
  • callback Function optional function to filter/modify focusable elements

Returns Function cleanup function to restore previous focus

traverse

Walks a DOM tree and calls callback for each node

Parameters

  • el Element root element to traverse
  • callback Function function called for each node
  • filter number NodeFilter constant (default: NodeFilter.SHOW_ELEMENT)

uid

Generates a unique base-16 string ID

Parameters

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

Returns string unique identifier

validate

Validates data against a set of rules

Parameters

  • data Object data to validate
  • rules Object 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

  • delay number 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); // 2

Returns number wrapped index