Skip to content

Docs

Install dtutils and use it from your code, in JavaScript and Python.

JavaScript

Install @dimitristerzz/dtutils with your package manager.

$ npm install @dimitristerzz/dtutils
$ bun add @dimitristerzz/dtutils
$ pnpm add @dimitristerzz/dtutils
$ yarn add @dimitristerzz/dtutils

The package is ES modules only. Add "type": "module" to your package.json, or use .mjs files.

formatColor

Converts a color between hex, RGB and HSL. Takes a hex string (with or without #, 3 or 6 digits), a comma-separated RGB string, or an RGB object.

formatColor(input: string | RGB, to: "hex" | "rgb" | "hsl"): string | RGB | HSL | null

Parameters

inputstring | RGB
"#FF8800", "f80", "255,136,0" or { r: 255, g: 136, b: 0 }.
to"hex" | "rgb" | "hsl"
The format to convert to.

Returns

Hex as an uppercase string with #, RGB as { r, g, b }, HSL as { h, s, l } with h from 0 to 360 and s and l from 0 to 100 (not rounded). null when the input or the format is invalid.

Example

import { formatColor } from "@dimitristerzz/dtutils";

formatColor("#f80", "rgb");     // { r: 255, g: 136, b: 0 }
formatColor("255,0,0", "hex");  // "#FF0000"
formatColor("#FFFFFF", "hsl");  // { h: 0, s: 0, l: 100 }
formatColor("300,0,0", "hex");  // null, 300 is out of range

randomInt

Returns a random integer between min and max, both included. The two ends can come in either order.

randomInt(min: number, max: number): number

Parameters

minnumber
One end of the range.
maxnumber
The other end of the range.

Returns

An integer from min to max.

Example

import { randomInt } from "@dimitristerzz/dtutils";

randomInt(1, 6);   // 1, 2, 3, 4, 5 or 6
randomInt(10, 1);  // same as randomInt(1, 10)

clamp

Keeps a number inside a range. The two bounds can come in either order.

clamp(value: number, min: number, max: number): number

Parameters

valuenumber
The number to limit.
minnumber
One bound of the range.
maxnumber
The other bound of the range.

Returns

value when it is inside the range, otherwise the nearest bound.

Example

import { clamp } from "@dimitristerzz/dtutils";

clamp(15, 0, 10);  // 10
clamp(-3, 0, 10);  // 0
clamp(4, 10, 0);   // 4

formatBytes

Turns a byte count into a readable size, from B up to PB, using 1024 per step.

formatBytes(bytes: number, decimals?: number): string

Parameters

bytesnumber
The size in bytes. Negative numbers keep their sign.
decimalsnumber
The most decimals to show. Defaults to 1, trailing zeros are dropped.

Returns

A string like "1.5 MB". "0 B" when bytes is not a finite number.

Example

import { formatBytes } from "@dimitristerzz/dtutils";

formatBytes(1536);              // "1.5 KB"
formatBytes(1048576);           // "1 MB"
formatBytes(5_000_000_000, 2);  // "4.66 GB"

slugify

Turns text into a lowercase, URL-friendly slug. Accents are removed and anything that isn't a letter or digit becomes a separator.

slugify(text: string, separator?: string): string

Parameters

textstring
The text to convert.
separatorstring
What goes between words. Defaults to "-".

Returns

The slug, with no separator at the start or end.

Example

import { slugify } from "@dimitristerzz/dtutils";

slugify("Hello, World!");      // "hello-world"
slugify("Crème Brûlée 2026");  // "creme-brulee-2026"
slugify("My File", "_");       // "my_file"

chunk

Splits an array into groups of the same size. Handy for batching requests or laying out grids.

chunk<T>(array: T[], size: number): T[][]

Parameters

arrayT[]
The array to split. It is not changed.
sizenumber
Items per group. Must be a positive integer, otherwise it throws a RangeError.

Returns

A new array of groups. The last group holds whatever is left, so it can be smaller.

Example

import { chunk } from "@dimitristerzz/dtutils";

chunk([1, 2, 3, 4, 5], 2);  // [[1, 2], [3, 4], [5]]

for (const batch of chunk(ids, 50)) {
  await saveMany(batch);
}

groupBy

Groups the items of an array by a property or by whatever a function returns for each item.

groupBy<T, K>(array: T[], key: keyof T | ((item: T) => K)): Record<K, T[]>

Parameters

arrayT[]
The array to group.
keykeyof T | (item: T) => K
A property name, or a function that returns the group for an item.

Returns

An object with one key per group, each holding its items in their original order.

Example

import { groupBy } from "@dimitristerzz/dtutils";

const users = [
  { name: "Ana", role: "admin" },
  { name: "Ben", role: "user" },
  { name: "Cy", role: "admin" },
];

groupBy(users, "role");
// { admin: [Ana, Cy], user: [Ben] }

groupBy([1, 2, 3, 4], (n) => (n % 2 ? "odd" : "even"));
// { odd: [1, 3], even: [2, 4] }

unique

Removes duplicates from an array and keeps the first copy of each. Pass a key to compare objects by one of their values.

unique<T>(array: T[], key?: keyof T | ((item: T) => unknown)): T[]

Parameters

arrayT[]
The array to dedupe. It is not changed.
keykeyof T | (item: T) => unknown
Optional. A property name or a function to compare items by. Without it, items are compared with ===.

Returns

A new array without duplicates, in the original order.

Example

import { unique } from "@dimitristerzz/dtutils";

unique([1, 1, 2, 3, 3]);                    // [1, 2, 3]
unique([{ id: 1 }, { id: 1 }, { id: 2 }], "id");  // [{ id: 1 }, { id: 2 }]
unique(emails, (e) => e.toLowerCase());

sleep

Waits for a number of milliseconds. Use it with await to pause an async function.

sleep(ms: number): Promise<void>

Parameters

msnumber
How long to wait, in milliseconds.

Returns

A promise that resolves after ms milliseconds.

Example

import { sleep } from "@dimitristerzz/dtutils";

console.log("Starting");
await sleep(1000);
console.log("One second later");

debounce

Wraps a function so it only runs once calls stop for wait milliseconds. Good for search boxes, resize and autosave.

debounce(fn: (...args) => void, wait: number): ((...args) => void) & { cancel(): void }

Parameters

fn(...args) => void
The function to run.
waitnumber
Milliseconds to wait after the last call.

Returns

A function that takes the same arguments as fn and runs it with the latest ones. Call .cancel() on it to drop a pending run.

Example

import { debounce } from "@dimitristerzz/dtutils";

const search = debounce((query: string) => {
  fetch(`/api/search?q=${query}`);
}, 300);

input.addEventListener("input", () => search(input.value));

throttle

Wraps a function so it runs at most once every wait milliseconds. The first call runs right away, and the last call made during the wait runs when it ends.

throttle(fn: (...args) => void, wait: number): ((...args) => void) & { cancel(): void }

Parameters

fn(...args) => void
The function to run.
waitnumber
The fewest milliseconds between two runs.

Returns

A function that takes the same arguments as fn. Call .cancel() on it to drop a pending run.

Example

import { throttle } from "@dimitristerzz/dtutils";

const onScroll = throttle(() => {
  console.log(window.scrollY);
}, 100);

window.addEventListener("scroll", onScroll);

retry

Runs an async function and tries again when it throws, waiting longer before each new try.

retry<T>(fn: (attempt: number) => Promise<T>, options?: RetryOptions): Promise<T>

Parameters

fn(attempt: number) => Promise<T>
The function to run. It gets the attempt number, starting at 1.
options.retriesnumber
How many times to try again after the first failure. Defaults to 3.
options.delaynumber
Milliseconds to wait before the first retry. Defaults to 500.
options.factornumber
Multiplies the wait after each retry. Defaults to 2, so 500, 1000, 2000.
options.onError(error, attempt) => boolean | void
Called after each failure. Return false to stop retrying and throw right away.

Returns

Whatever fn resolves with. When every attempt fails, it throws the last error.

Example

import { retry } from "@dimitristerzz/dtutils";

const data = await retry(
  async () => {
    const res = await fetch("/api/data");
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    return res.json();
  },
  { retries: 5, delay: 250 },
);

tryCatch

Awaits a promise and hands back the error and the result as a pair, so you can skip the try/catch block.

tryCatch<T, E = Error>(promise: Promise<T>): Promise<[null, T] | [E, null]>

Parameters

promisePromise<T>
The promise to await.

Returns

[null, data] when the promise resolves, [error, null] when it rejects. It never throws.

Example

import { tryCatch } from "@dimitristerzz/dtutils";

const [error, user] = await tryCatch(getUser(id));
if (error) {
  console.error(error.message);
  return;
}
console.log(user.name);

Python

Install dtutils_dimitristerzz with pip, together with the two libraries it uses, then import it as dtutils. Needs Python 3.9 or newer. The functions take the same names as their JavaScript versions.

$ pip install dtutils_dimitristerzz requests python-dotenv

getInput

Fetches a page as text, sending SC from your .env as its session cookie. Handy for inputs behind a login, like Advent of Code puzzles.

getInput(url: str) -> str

Parameters

urlstr
The page to fetch.

Returns

The response body as a string. The .env is looked up in the current folder and its subfolders first, then in each parent folder.

Example

# .env
SC=your-session-cookie

# main.py
from dtutils import getInput

data = getInput("https://adventofcode.com/2025/day/1/input")
print(data.splitlines()[0])

chunk

Splits a list, or any iterable, into groups of the same size.

chunk(items: Iterable, size: int) -> list[list]

Parameters

itemsIterable
The items to split.
sizeint
Items per group. Must be a positive integer, otherwise it raises a ValueError.

Returns

A new list of groups. The last group holds whatever is left, so it can be smaller.

Example

from dtutils import chunk

chunk([1, 2, 3, 4, 5], 2)  # [[1, 2], [3, 4], [5]]
chunk("abcdef", 3)         # [['a', 'b', 'c'], ['d', 'e', 'f']]

clamp

Keeps a number inside a range. The two bounds can come in either order.

clamp(value, low, high)

Parameters

valueint | float
The number to limit.
lowint | float
One bound of the range.
highint | float
The other bound of the range.

Returns

value when it is inside the range, otherwise the nearest bound.

Example

from dtutils import clamp

clamp(15, 0, 10)   # 10
clamp(-3, 0, 10)   # 0
clamp(0.5, 1, 0)   # 0.5

slugify

Turns text into a lowercase, URL-friendly slug. Accents are removed and anything that isn't a letter or digit becomes a separator.

slugify(text: str, separator: str = "-") -> str

Parameters

textstr
The text to convert.
separatorstr
What goes between words. Defaults to "-".

Returns

The slug, with no separator at the start or end.

Example

from dtutils import slugify

slugify("Hello, World!")      # "hello-world"
slugify("Crème Brûlée 2026")  # "creme-brulee-2026"
slugify("My File", "_")       # "my_file"

formatBytes

Turns a byte count into a readable size, from B up to PB, using 1024 per step.

formatBytes(size: int | float, decimals: int = 1) -> str

Parameters

sizeint | float
The size in bytes. Negative numbers keep their sign.
decimalsint
The most decimals to show. Defaults to 1, trailing zeros are dropped.

Returns

A string like "1.5 MB".

Example

import os
from dtutils import formatBytes

formatBytes(1536)                       # "1.5 KB"
formatBytes(5_000_000_000, 2)           # "4.66 GB"
formatBytes(os.path.getsize("video.mp4"))

retry

A decorator that runs the function again when it raises, waiting longer before each new try.

@retry(retries: int = 3, delay: float = 0.5, factor: float = 2, exceptions: tuple = (Exception,))

Parameters

retriesint
How many times to try again after the first failure. Defaults to 3.
delayfloat
Seconds to wait before the first retry. Defaults to 0.5.
factorfloat
Multiplies the wait after each retry. Defaults to 2, so 0.5, 1, 2.
exceptionstuple[type[Exception], ...]
Only these errors trigger a retry. Anything else is raised right away.

Returns

The decorated function. It returns what the original returns, or raises the last error once the retries run out.

Example

import requests
from dtutils import retry

@retry(retries=5, delay=1, exceptions=(requests.RequestException,))
def fetch_status():
    res = requests.get("https://example.com/api/status", timeout=5)
    res.raise_for_status()
    return res.json()