Collection · 28 utilities

Misc utilities

Conversions, runtime checks, cookies, timers and sequencing: small helpers that do not fit another section, with their limits written down.

Convert Celsius to Fahrenheit

Apply the temperature conversion without rounding the result.

function toFahrenheit(value) { return value * 9 / 5 + 32; }misc

Convert hex to RGB

Expand #rgb if needed and read the red, green and blue channels.

function hexToRgb(hex) { return hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i, (_, r, g, b) =>…misc

Convert URL parameters to object

Read a query string into an object; repeated keys become arrays.

function getUrlParams(query) { return Array.from(new URLSearchParams(query)).reduce((params, [k…misc

Convert Fahrenheit to Celsius

Subtract 32 and multiply by 5/9.

function fahrenheitToCelsius(fahrenheit) { return (fahrenheit - 32) * 5 / 9; }misc

Get the value of a param from a URL

Parse an absolute URL and read one query parameter.

function getParam({ url, param }) { return new URL(url).searchParams.get(param); }misc

Convert RGB color to hex

Pack three 0–255 channels into a #rrggbb string.

function rgbToHex({ red, green, blue }) { return `#${((1 << 24) + (red << 16) + (green << 8) + …misc

Convert cookie to object

Parse a Cookie header string into name–value pairs.

function parseCookies(cookie) { return Object.fromEntries(cookie.split(';').filter(item => item…misc

Easing functions

Evaluate a common easing curve at progress t between 0 and 1.

function ease({ name, t }) { return { linear: t, easeInQuad: t * t, easeOutQuad: t * (2 - t), e…misc

Encode a URL component strictly

Percent-encode a value, including !'()* that encodeURIComponent leaves alone.

function encodeStrict(value) { return encodeURIComponent(value).replace(/[!'()*]/g, char => `%$…misc

Get the value of a cookie

Find one cookie by name in a Cookie header string.

function getCookie({ cookie, name }) { const match = `; ${cookie}`.split(`; ${name}=`); return …misc

Get the type of a variable as a string

Read the internal [[Class]] tag via Object.prototype.toString.

function getTypeOf(value) { return Object.prototype.toString.call(value).match(/\[object (.*)\]…misc

Swap two variables

Exchange two values with array destructuring.

function swap([a, b]) { [a, b] = [b, a]; return [a, b]; }misc

Decode a JWT token

Read the JSON payload of a JSON Web Token — without verifying it.

function decodeJwtPayload(token) { const base64 = token.split('.')[1].replace(/-/g, '+').replac…misc

Get the first defined and non-null value

Return the first item that is neither null nor undefined.

function coalesce(values) { return values.find(item => item !== undefined && item !== null) ?? …misc

Convert a Lab color to an LCH color

Turn a and b into chroma and hue degrees.

function labToLch([l, a, b]) { return [l, Math.hypot(a, b), ((Math.atan2(b, a) * 180) / Math.PI…misc

Convert an LCH color to a Lab color

Turn chroma and hue degrees back into a and b.

function lchToLab([l, c, h]) { return [l, Math.cos((h * Math.PI) / 180) * c, Math.sin((h * Math…misc

Check if the code is running in Jest

Look for the JEST_WORKER_ID variable that Jest sets in its workers.

function isRunningInJest() { return typeof process !== 'undefined' && process.env.JEST_WORKER_I…misc

Clear all cookies

Expire every cookie that JavaScript can see on the current path.

function clearCookies() { for (const cookie of document.cookie.split(';')) { const name = cooki…misc

Detect dark mode

Read the prefers-color-scheme media feature.

function isDarkMode() { return window.matchMedia?.('(prefers-color-scheme: dark)').matches ?? f…misc

Emulate a dice throw

Return an integer from 1 to 6.

function throwDice() { return Math.floor(Math.random() * 6) + 1; }misc

Generate an unique and increment id

Create a counter that returns 0, 1, 2… on successive calls.

function createIdGenerator(start = 0) { let id = start; return () => id++; }misc

Run Promises in sequence

Start each task after the previous one finishes and collect the results in order.

async function runInSequence(tasks) { const results = []; for (const task of tasks) results.pus…misc

Wait for an amount of time

Return a promise that resolves after the given milliseconds.

function wait(milliseconds) { return new Promise(resolve => setTimeout(resolve, milliseconds));…misc

Wait for the next event loop

Resolve after the current task, letting queued timers, I/O and rendering run.

function nextTask() { return new Promise(resolve => setTimeout(resolve, 0)); }misc

Try a function in the local code lab, then read its limits before using it in an application.

Type two or more characters. Try “duplicate”, “webhook” or “retry”.