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

@catstral/levy-utils

v2.0.0

Published

Re-useable and common JS/TS utility functions

Readme

@catstral/levy-utils

@catstral/levy-utils is a lightweight, dependency-light library of common JS/TS utility functions covering everyday needs: array/object manipulation, type checks, async helpers, and value conversion.

How to install

Install with a package manager

# using npm
npm install @catstral/levy-utils

# using yarn
yarn add @catstral/levy-utils

# using pnpm
pnpm add @catstral/levy-utils

# using bun
bun add @catstral/levy-utils

Usage

import { range, sift, toggle } from "@catstral/levy-utils";

Utils

A list of all the utilities supported:

Array utilities

cluster(items, size)

Clusters a list of items into a list of lists, each limited to a specified size.

cluster([1, 2, 3, 4, 5], 2);
// Expected output:
// [[1, 2], [3, 4], [5]]

concat(...values)

Concatenates values and arrays into a new array.

concat(1, [2, 3], 4);
// Expected output:
// [1, 2, 3, 4]

counting(list, identity)

Reduces a list down to an object of keys (as determined by the identity callback) mapped to how many times that key occurred.

counting(["a", "b", "a", "c", "a"], (item) => item);
// Expected output:
// {
//     a: 3,
//     b: 1,
//     c: 1
// }

filter(list, predicate)

Returns a new list containing the items of a given list that pass a predicate.

If the predicate returns a promise for any item, a promise is returned that resolves once all of them have.

filter([1, 2, 3, 4], (n) => n % 2 === 0);
// Expected output:
// [2, 4]

await filter([1, 2, 3], async (n) => n > 1);
// Expected output:
// [2, 3]

filterMap(list, filter, mapper)

Returns a new list of items based on filtered and mapped values of a given list.

filterMap(
    [1, 2, 3, 4],
    (n) => n % 2 === 0,
    (n) => n * 10,
);
// Expected output:
// [20, 40]

This utility was formerly called select.

first(list, fallback?)

Returns the first item of a list, or a fallback if the list is empty.

first([1, 2, 3]);
// Expected output:
// 1

first([], "none");
// Expected output:
// "none"

fork(list, condition)

Splits a list into a tuple of two arrays based on a condition: items that pass, and items that don't.

fork([1, 2, 3, 4], (n) => n % 2 === 0);
// Expected output:
// [[2, 4], [1, 3]]

group(list, identity)

Groups the items of a list into an object of keys (as determined by the identity callback) mapped to the items with that key.

group(["apple", "avocado", "banana"], (item) => item[0]);
// Expected output:
// {
//     a: ["apple", "avocado"],
//     b: ["banana"],
// }

hasItems(list)

Checks if a list has at least one item, narrowing its type to a non-empty tuple.

hasItems([1, 2, 3]);
// Expected output:
// true

hasItems([]);
// Expected output:
// false

last(list, fallback?)

Returns the last item of a list, or a fallback if the list is empty.

last([1, 2, 3]);
// Expected output:
// 3

last([], "none");
// Expected output:
// "none"

list(startOrLength, end?, options?)

Returns an array with values to a specified size (inclusive), optionally stepped and/or mapped to another value.

list(3)
// Expected output:
// [0, 1, 2, 3]

list(0, 3)
// Expected output:
// [0, 1, 2, 3]

list(0, 6, {
    step: 2,
})
// Expected output:
// [0, 2, 4, 6]

list(0, 3, {
    valueMapper: (step) => `foo-${step}`,
})
// Expected output:
// ["foo-0", "foo-1", "foo-2", "foo-3"]

options:

  • step - The steps used to generate the array.
  • valueMapper - A mapper function to map a step to a value.

map(list, callback)

Returns a new list of items based on mapped values of a given list.

If the callback returns a promise for any item, a promise is returned that resolves once all of them have.

map([1, 2, 3], (n) => n * 2);
// Expected output:
// [2, 4, 6]

await map([1, 2, 3], async (n) => n + 1);
// Expected output:
// [2, 3, 4]

max(list, mapper?, options?)

Returns the largest item from a list.

max([1, 2, 3]);
// Expected output:
// 3

max(
    [
        {
            name: "Bob"
            weight: 54
        },
        {
            name: "Paul"
            weight: 87
        },
        {
            name: "Jane"
            weight: 63
        },
    ],
    (item) => item.weight,
);
// Expected output:
// {
//     name: "Paul",
//     weight: 87,
// }

min(list, mapper?, options?)

Returns the smallest item from a list.

min([1, 2, 3]);
// Expected output:
// 1

min(
    [
        {
            name: "Bob"
            weight: 54
        },
        {
            name: "Paul"
            weight: 87
        },
        {
            name: "Jane"
            weight: 63
        },
    ],
    (item) => item.weight,
);
// Expected output:
// {
//     name: "Bob",
//     weight: 54,
// }

overflow(list, clampLength)

Splits a list into a tuple of two arrays: the first clampLength items, and the rest of the items.

Throws an OverflowUtilError if the clamp length is negative or the given list is not an array.

overflow([1, 2, 3, 4, 5], 3);
// Expected output:
// [[1, 2, 3], [4, 5]]

reduce(list, initial, callback, options?)

Reduces all items of a list down to an accumulated result.

reduce([1, 2, 3], 0, (acc, n) => acc + n);
// Expected output:
// 6

reduce(["a", "b", "c"], "", (acc, letter) => acc + letter, {
    direction: "DESCENDING",
});
// Expected output:
// "cba"

reduce([1, 2, 3], 0, (acc, n) => acc + n, {
    result: (total) => `Total: ${total}`,
});
// Expected output:
// "Total: 6"

Options:

  • direction - "ASCENDING" or "DESCENDING", determines the order the list is reduced in (default "ASCENDING")
  • result - transforms the final accumulator into the returned result

select(list, callback)

Returns a new list built by deciding, per item, what should end up in the result. The callback receives a context object and must return one of its actions.

select(
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    ({ item, keep, discard, filter }) => {
        if (item < 3) {
            return keep();
        }
    
        if (item > 8) {
            return discard();
        }
    
        return filter(item % 2 === 0);
    },
);
// Expected output:
// [1, 2, 4, 6, 8]

select<number | string[] | null, string>(
    [1, ["2", "3", "4"], null, ["7", "8", "9"], 10],
    ({ item, map, flat, spread }) => {
        if (typeof item === "number") {
            return map(item.toString());
        }

        if (Array.isArray(item)) {
            return flat(item);
        }

        return spread("5", "6");
    },
);
// Expected output:
// ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]

Available actions:

  • keep() - keeps the current item
  • discard() - removes the current item
  • filter(keep) - keeps or removes the current item based on a boolean
  • map(value) - replaces the current item with a value
  • flat(values) - replaces the current item with every value of a list
  • spread(...values) - replaces the current item with every given value

Throws a SelectUtilError if the callback returns an invalid action.

This utility was reworked, it's old behaviour has moved to the filterMap utility.

sift(list)

Filters all falsy values out of a list.

Falsy values are:

  • false
  • 0
  • 0n (bigint 0)
  • ""
  • null
  • undefined
sift([1, 0, 2, null, 3, undefined, false]);
// Expected output:
// [1, 2, 3]

sum(list, mapper?)

Sums a list of items into a total number.

sum([1, 2, 3]);
// Expected output:
// 6

sum([1, 2, 3], (n) => n * 2);
// Expected output:
// 12

sum([false, true, "", "Hello", null, {}, undefined, []]);
// Expected output:
// 4

sum(["3", "4", "5"], (item) => Number.parseInt(item, 10));
// Expected output:
// 12

toggle(list, itemToToggle, options?)

Toggles a value in an array: removes it if present, adds it if not.

toggle([1, 2, 3], 2);
// Expected output:
// [1, 3]

toggle([1, 2, 3], 4);
// Expected output:
// [1, 2, 3, 4]

toggle([1, 2, 3], 4, {
    strategy: "PREPEND",
});
// Expected output:
// [4, 1, 2, 3]

toggle(
    [{ id: 1 }, { id: 2 }],
    {
        id: 1,
    },
    {
        toKey: (item) => item.id,
    },
);
// Expected output:
// [{ id: 2 }]

Options:

  • toKey - maps an item to a key used to determine equality (defaults to comparing items directly)
  • strategy - "APPEND" or "PREPEND", determines where new items are inserted (default "APPEND")

Callback utilities

chain(...callbacks)

Chains many callbacks together, with each callback accepting the result of the previous one as an argument, returning the result of the final callback.

Note: due to a TypeScript limitation, the argument of each chained callback requires a type hint in order to infer the argument correctly (it does not allow passing an invalid argument type however).

// note the type hint for the argument
chain(() => true, (value: boolean) => value ? "true" : "false");
// Expected output:
// "true"

compose(...callbacks)

Turns many callbacks into a single re-usable callback.

const fn = compose(
    (n: number) => n + 1,
    (n: number) => n * 2,
);

fn(2);
// Expected output:
// 6

fn(5);
// Expected output:
// 12

defer(callback)

Defers a callback to the next execution cycle.

defer(() => console.log("runs after the current call stack clears"));

noop()

No operation, this function does nothing. Useful for placeholder code.

noop();
// Expected output:
// undefined

pipe(value, callback)

Pipes a value into a callback and returns its result.

pipe(5, (n) => n * 2);
// Expected output:
// 10

pipe("Foo", (value) => `${value} Bar`);
// Expected output:
// "Foo Bar"

preset(callback, parameters)

Presets the parameters of a callback with a callback that computes its arguments.

const fn = preset(
    Number.parseInt,
    (value: string): [string, number] => [value, 10],
);

fn("10");
// Expected output:
// 10

fn("3.2");
// Expected output:
// 3

preset(Number.parseInt, ["0", 10])();
// Expected output:
// 0

retry(callback, options?)

Retries an async (or sync) callback until it succeeds or the maximum number of attempts is reached.

await retry(() => fetchSomething(), {
    attempts: 5,
    delay: 500,
    backoff: true,
    onRetry: (error, attempt) => console.log(`attempt ${attempt} failed`, error),
});

Options:

  • attempts - maximum number of attempts (default 3)
  • delay - delay between retries in milliseconds (default 1000)
  • backoff - whether to double the delay after each retry (default false)
  • onRetry - callback invoked with the error and attempt number on each failed attempt

task(callback?)

Executes the given callback in asynchronous context.

// This yields execution to the microtask queue.
await task();

// A task that has a seperate asynchronous flow 
task(async () => {
    await doSomething();
});

miscellaneous utilities

compute(value, ...args) / isComputation(value)

compute resolves a Computable<T> - either a plain value or a function that produces one - calling it with the given args if it's a function. isComputation checks whether a Computable<T> is the function variant.

compute(5);
// Expected output:
// 5

compute((a: number, b: number) => a + b, 2, 3);
// Expected output:
// 5

identity(value)

Returns the given value as is, with its type inferred as narrowly as possible (as a const generic).

identity(5);
// Expected output:
// 5

identity({
    a: 1,
});
// Expected output:
// {
//     a: 1,
// }

isEmpty(value)

Checks if a value is considered empty.

All values that are considered empty:

  • An empty array ([])
  • An empty object ({}) (This checks for keys, if a key exist but has no values it will not be counted as empty, see example)
  • An empty string ("")
  • null
  • undefined
isEmpty([]);
// Expected output:
// true

isEmpty({});
// Expected output:
// true

isEmpty("");
// Expected output:
// true

isEmpty(null);
// Expected output:
// true

isEmpty({
    a: undefined,
});
// Expected output:
// false (the key exists)

isNull(value)

Checks if a value is null.

isNull(null);
// Expected output:
// true

isNull(undefined);
// Expected output:
// false

isNullish(value)

Checks if a value is nullish: null or undefined.

isNullish(null);
// Expected output:
// true

isNullish(undefined);
// Expected output:
// true

isNullish(0);
// Expected output:
// false

isPrimitive(value)

Checks if a value is a primitive: string, number, boolean, symbol, null, or undefined.

isPrimitive("foo");
// Expected output:
// true

isPrimitive({});
// Expected output:
// false

isPromise(value)

Checks if a value is a Promise (an instance of Promise).

isPromise(Promise.resolve(1));
// Expected output:
// true

isPromise({ 
    then: () => {},
});
// Expected output:
// false

isPromiseLike(value)

Checks if a value is promise-like: an object with a then function.

isPromiseLike(Promise.resolve(1));
// Expected output:
// true

isPromiseLike({
    then: () => {},
});
// Expected output:
// true

isPromiseLike({});
// Expected output:
// false

isUndefined(value)

Checks if a value is undefined.

isUndefined(undefined);
// Expected output:
// true

isUndefined(null);
// Expected output:
// false

match(value, clause, fallback?)

Matches a value to a clause that return a value and returns a fallback if none of the cases match.

const fn = (value: string) => {
    return match(
        value,
        {
            A: 1,
            B: 2,
        },
        -1,
    );
};

fn("A");
// Expected output:
// 1

fn("B");
// Expected output:
// 2

fn("C");
// Expected output:
// -1

Range(rangeString?)

The constructor of this has an overload:
Range(details?)

Details:

  • start - The start value of the range (optional).
  • inclusiveStart - If the range should consider the start to be inclusive (optional).
  • end - The end value of the range (optional)
  • inclusiveEnd - If the range should consider the end to be inclusive (optional).
  • step - The step value of the range (optional).
  • mapper - The mapper of the range, this maps a step to a value (optional).

This is a class representing a range value, it is an iterable and generates values based on a start and end value (if specified).

If no start of end value is specified the range will work as expected with methods, but trying to iterate over it will throw an error.

It can also be given a step and a mapper to define how it should be generating a value.

If the argument given is a string, then it is expected to have that string match the following definition: S?>?..=?E? where:

  • S - The start of the range (optional)
  • E - The end of the range (optional)
  • > - If the start value is exclusive of this range (optional)
  • = - If the end value is inclusive of this range (optional)

Here is a simple table explaining the different types of range strings: | Syntax | Range | Is iterable | | -------------------| --------------- | ----------- | | [start]..[end] | start ≤ x < end | Yes | | [start]>..[end] | start < x < end | Yes | | [start]..=[end] | start ≤ x ≤ end | Yes | | [start]>..=[end] | start < x ≤ end | Yes | | .. | - | No | | [start].. | start ≤ x | No | | [start]>.. | start < x | No | | ..[end] | x < end | No | | ..=[end] | x ≤ end | No |

If a value is not iterable, that means it will throw an error on attempting to iterate the range.
A full range is a range without bounds, this mostly exists for completeness and would effect how certain methods of the range work, see the methods for more details on how they are effected.

This class can also be gotten from the range utility function.

static from(range)

Creates a new range with the details from the specified range.

This does the same as Range.clone

details (getter)

Gets the internal details of the Range.

This is a getter, no value can be set here.

start (getter)

Gets the start value of range.

This is a getter, no value can be set here.

end (getter)

Gets the end value of range.

This is a getter, no value can be set here.

step (getter)

Gets the step value of range.

This is a getter, no value can be set here.

mapper (getter)

Gets the mapper value of range.

This is a getter, no value can be set here.

start(start?)

Creates a new Range with a given start value set.

inclusiveStart(inclusiveStart)

Creates a new Range with a given inclusive start value set.

end(end?)

Creates a new Range with a given end value set.

inclusiveEnd(inclusiveEnd)

Creates a new Range with a given inclusive end value set.

step(step?)

Creates a new Range with a given step value set.

map(mapper)

Creates a new Range with a given mapper set.

includes(value)

Returns a boolean to signal if the given value is included in the range.

Notes:

  • If the range is a full range, then this will always return true.
  • NaN will always return false (unless the range is a full range).
excludes(value)

Returns a boolean to signal if the given value is excluded from the range.

Notes:

  • If the range is a full range, then this will always return false.
  • NaN will always return false.
toArray()

Returns an array based on the values of the range.

clone()

Returns a new Range with same details.

This does the same as static Range.from

range(startOrLength, end?, options?)

Returns a Range that yields values over a specified range (inclusive), optionally stepped and/or mapped to another value.

for (const value of range(3)) {
    console.log(value);
}
// Expected output:
// logs 0, 1, 2, 3

for (const value of range(0, 3)) {
    console.log(value);
}
// Expected output:
// logs 0, 1, 2, 3

for (const value of range(0, 6, {
    step: 2,
})) {
    console.log(value);
}
// Expected output:
// logs 0, 2, 4, 6

for (const value of range(0, 3, {
    valueMapper: (step) => `foo-${step}`,
})) {
    console.log(value);
}
// Expected output:
// logs "foo-0", "foo-1", "foo-2", "foo-3"

for (const value of range(0, 3, {
    inclusiveStart: false,
})) {
    console.log(value);
}
// Expected output:
// logs 1, 2, 3

for (const value of range(0, 3, {
    inclusiveEnd: false,
})) {
    console.log(value);
}
// Expected output:
// logs 0, 1, 2

options:

  • step - The steps used to generate the array.
  • valueMapper - A mapper function to map a step to a value.
  • inclusiveStart - Wether the start value is considered inclusive.
  • inclusiveEnd - Wether the end value is considered inclusive.

NOTE: inclusiveEnd default value here differs from the inclusiveEnd value set by Range, this is for backwards compatibility.

raise(value)

Throws the given value, never returns.

  • A string is wrapped in an Error.
  • A function is called without arguments and its result is thrown.
  • Any other value is thrown as is.

This is useful for throwing in expression positions, such as a fallback.

raise("Something went wrong");
// Expected to throw:
// Error("Something went wrong")

raise(() => new RangeError("Out of range"));
// Expected to throw:
// RangeError("Out of range")

readOnly(value, deepFreeze?) / isReadOnly(value)

readOnly returns a read-only copy of an object, array, map, or set.

isReadOnly checks if a value is frozen.

const original = {
    a: 1,
    nested: {
        b: 2
    }
};
const shallow = readOnly(original);
const deep = readOnly(original, true);

isReadOnly(shallow);
// Expected output:
// true

shallow.nested === original.nested;
// Expected output:
// true (nested values are shared and still mutable)

deep.nested === original.nested;
// Expected output:
// false (nested values are cloned and frozen)

isReadOnly(original);
// Expected output:
// false

safe(callback)

Executes the given callback and returns an option of the result.

safe(() => {
    return "Hello world";
});
// Expected output:
// {
//     success: true,
//     value: "Hello world",
// }

safe(() => {  
    throw new Error("Goodbye world");
});
// Expected output:
// {
//     success: false,
//     error: Error("Goodbye world"),
// }

sleep(delay)

Returns a promise that resolves after the specified delay (in milliseconds).

await sleep(1000);
// Expected output:
// waits 1 second

timeout(value, delayMs, options?) / isTimeoutError(value)

Wraps a promise (or a callback that returns one) into a promise that rejects with a TimeoutError if it hasn't settled after the given delay (in milliseconds). If the promise settles first, its result (or error) is passed through.

When given a callback, it receives an AbortSignal which is aborted when the delay elapses, so the underlying operation can be cancelled.

isTimeoutError checks if a value is a TimeoutError.

await timeout(sleep(100), 1000);
// Expected output:
// resolves after 100ms

await timeout(sleep(2000), 1000);
// Expected to throw:
// TimeoutError("The operation was timed out after 1000ms")

await timeout(
    (signal) => fetch("https://example.com", { 
        signal,
    }),
    1000,
);
// Expected output:
// the response, or a rejection (and an aborted request) if it takes longer than 1 second

try {
    await timeout(sleep(2000), 1000);
} catch (error) {
    isTimeoutError(error);
    // Expected output:
    // true
}

Options:

  • onTimeout - a callback invoked with the delay when it elapses. Throwing inside it rejects the promise with the thrown value instead of a TimeoutError.

unwrap(option, fallback?)

Directly returns the option's value, or throws the option's error. An option's error won't be thrown when a fallback is provided.

const option = safe(() => {
    throw new Error("Goodbye world");
});

unwrap(option);
// Expected to throw:
// Error("Goodbye world")

unwrap(option, null);
// Expected output:
// null

values(target)

Returns an array of values based on the given target.

values([1, 2, 3]);
// Expected output:
// [1, 2, 3]

values(new Set([4, 5, 6]));
// Expected output:
// [4, 5, 6]

values({
  A: "a",
  B: "b",
  C: "c",
});
// Expected output:
// ["a", "b", "c"]

values(new Map([
  ["D", "d"],
  ["E", "e"],
  ["F", "f"],
]));
// Expected output:
// ["d", "e", "f"]

Number utilities

Math utilities

isPrime(value)

Checks if the given value is a prime number.

isPrime(11);
// Expected output:
// true

isPrime(4);
// Expected output:
// false

isPrime(103);
// Expected output:
// true

isPrime(-9.2);
// Expected output:
// false
mod(dividend, divisor)

Returns the modulo of a dividend and a divisor.

mod(10, 5);
// Expected output:
// 0

mod(-2, 4);
// Expected output:
// 2

mod(6, 10);
// Expected output:
// 6

clamp(min, value, max)

Clamps a number between a minimum and maximum value.

clamp(-5, 0, 5);
// Expected output:
// 0

clamp(-5, 20, 5);
// Expected output:
// 5

clamp(-5, -20, 5);
// Expected output:
// -5

isDecimal(value)

Checks if the given value is a number with decimals.

isDecimal(1.1);
// Expected output:
// true

isDecimal(1);
// Expected output:
// false

isDecimal(NaN);
// Expected output:
// false

isEven(value)

Checks if the given value is an even number.

isEven(4);
// Expected output:
// true

isEven(3);
// Expected output:
// false

isEven(0.5);
// Expected output:
// false

isInteger(value)

Checks if the given value is an integer.

isInteger(4);
// Expected output:
// true

isInteger(4.5);
// Expected output:
// false

isNegative(value)

Checks if the given value is a negative number.

isNegative(-5);
// Expected output:
// true

isNegative(5);
// Expected output:
// false

isNegative(-0);
// Expected output:
// true

isOdd(value)

Checks if the given value is an odd number.

isOdd(3);
// Expected output:
// true

isOdd(4);
// Expected output:
// false

isOdd(0.5);
// Expected output:
// false

isPositive(value)

Checks if the given value is a positive number.

isPositive(5);
// Expected output:
// true

isPositive(-5);
// Expected output:
// false

isPositive(0);
// Expected output:
// true

negative(value)

Converts a number into a negative number.

negative(5);
// Expected output:
// -5

negative(-5);
// Expected output:
// -5

positive(value)

Converts a number into a positive number.

positive(-5);
// Expected output:
// 5

positive(5);
// Expected output:
// 5

sign(value)

Returns the sign of the given number: 1 if positive, -1 if negative, 0 if zero (NaN is converted into zero).

sign(5);
// Expected output:
// 1

sign(-5);
// Expected output:
// -1

sign(0);
// Expected output:
// 0

sign(NaN);
// Expected output:
// 0

toFloat(value, fallback?)

Converts a value to a float, falling back to a default (0 by default) if the conversion fails or the value isn't a supported type.

toFloat("3.14");
// Expected output:
// 3.14

toFloat(true);
// Expected output:
// 1

toFloat("not a number", -1);
// Expected output:
// -1

toInt(value, fallback?)

Converts a value to an integer, falling back to a default (0 by default) if the conversion fails or the value isn't a supported type.

toInt("42");
// Expected output:
// 42

toInt(true);
// Expected output:
// 1

toInt("not a number", -1);
// Expected output:
// -1

trunc(value, fractionDigits?)

Truncates a number to the specified number of fraction digits.

trunc(1.58);
// Expected output:
// 1

trunc(1.456, 2);
// Expected output:
// 1.45

trunc(1.789, 10)
// Expected output:
// 1.789

Object utilities

entries(value)

A typed version of Object.entries.

entries({
    a: 1,
    b: "two",
});
// Expected output:
// [["a", 1], ["b", "two"]] (typed as [K, T[K]][])

extend(value, other)

Extends an object with another object.

extend(
    {
        key: "value",
    },
    {
        foo: "bar",
    },
);
// Expected output:
// {
//     key: "value",
//     foo: "bar",
// }

isObject(item)

Checks if a value is an object, excluding arrays.

isObject({});
// Expected output:
// true

isObject([]);
// Expected output:
// false

keys(value)

A typed version of Object.keys.

keys({
    a: 1,
    b: 2,
});
// Expected output:
// ["a", "b"] (typed as (keyof T)[])

omit(object, keys)

Returns a new object with the specified key(s) removed.

omit(
    {
        a: 1,
        b: 2,
        c: 3,
    },
    "b",
);
// Expected output:
// {
//     a: 1,
//     c: 3
// }

omit(
    {
        a: 1,
        b: 2,
        c: 3,
    },
    ["a", "c"],
);
// Expected output:
// {
//     b: 2
// }

pick(object, keys)

Returns a new object containing only the specified key(s).

pick(
    {
        a: 1,
        b: 2,
        c: 3,
    },
    "b",
);
// Expected output:
// {
//     b: 2
// }

pick(
    {
        a: 1,
        b: 2,
        c: 3,
    },
    ["a", "c"],
);
// Expected output:
// {
//     a: 1,
//     c: 3
// }

Randomization utilities

Almost all utilites that generate someting at random are done with a cryptographically secure pseudorandom number generator (called from now own CSPRNG) and utilizes the crypto.getRandomValues method. If a utility does not use this, it will be mentioned in the description of that utility.

UUID utilities

uuidMax()

Returns the max UUID string possible.

uuidMax();
// Expected output:
// "ffffffff-ffff-ffff-ffff-ffffffffffff"
uuidNil()

Returns the nil UUID string.

uuidNil();
// Expected output:
// "00000000-0000-0000-0000-000000000000"

uuidV1(options?)

This is also aliased to v1

Returns a randomly generated UUID V1 string.

uuidV1();
// Possible output:
// c232ab00-9414-11ec-b3c8-9f68deced846

uuidV1({
    random: Uint8Array.of(0, 0, 0, 0, 0, 0, 0, 0, 0x33c8 >> 8, 0x33c8 & 0xff, 0x9f, 0x68, 0xde, 0xce, 0xd8, 0x46),
    milliseconds: 0x17f22e279b0,
    nanoseconds: 0,
    clockSequence: 0x33c8,
    node: Uint8Array.of(0x9f, 0x68, 0xde, 0xce, 0xd8, 0x46),
})
// Expected output:
// c232ab00-9414-11ec-b3c8-9f68deced846

options:

  • random - The random bytes used to generate the UUID.
  • rng - A function to generate a list of random bytes for UUID generation.
  • milliseconds - A number that represents the amount of milliseconds from the EPOCH (number of milliseconds since 01-01-1970).
  • nanoseconds - A number that represents tha amount of nanoseconds have elapsed in the specified millisecond (This will always be 0 if not defined, javascript does not measure beyond the millisecond range).
  • clockSequence - The current clock sequence used for generation.
  • node - A list of random bytes used to complete the UUID V1.

uuidV4(options?)

This is also aliased to v4 or uuid

Returns a randomly generated UUID V4 string.

uuidV4();
// Possible output:
// 919108f7-52d1-4320-9bac-f847db4148a8

uuidV4({
    random: Uint8Array.of(0x91, 0x91, 0x08, 0xf7, 0x52, 0xd1, 0x43, 0x20, 0x9b, 0xac, 0xf8, 0x47, 0xdb, 0x41, 0x48, 0xa8),
})
// Expected output:
// 919108f7-52d1-4320-9bac-f847db4148a8

options:

  • random - The random bytes used to generate the UUID.
  • rng - A function to generate a list of random bytes for UUID generation.

uuidV7(options?)

This is also aliased to v7

Returns a randomly generated UUID V7 string.

uuidV7();
// Possible output:
// 017f22e2-79b0-7cc3-98c4-dc0c0c07398f

uuidV7({
    random: Uint8Array.of(0x10, 0x7f, 0x22, 0xe2, 0x79, 0xb0, 0x7c, 0xc3, 0x98, 0xc4, 0xdc, 0x0c, 0x0c, 0x07, 0x39, 0x8f),
    milliseconds: 0x017f22e279b0,
    sequence: 0xcc363137,
})
// Expected output:
// 017f22e2-79b0-7cc3-98c4-dc0c0c07398f

options:

  • random - The random bytes used to generate the UUID.
  • rng - A function to generate a list of random bytes for UUID generation.
  • milliseconds - A number that represents the amount of milliseconds from the EPOCH (number of milliseconds since 01-01-1970).
  • sequence - The current clock sequence used for generation.

chance(percentage)

Returns a random boolean based on the specified percentage.
The percentage must be a number between 0 and 1. If it is not inside that range it will return a fixed value according to that percentage, so if percentage is more than or equal to 1 it will always return true and if percentage is less than or equal to 0 it will always return false.

chance(0.5);
// Expected output:
// true | false

chance(1);
// Expected output:
// true

chance(0);
// Expected output:
// false

draw(list)

Returns a random item from a specified list (or undefined if the list is empty).

draw([0, 1, 2, 3]);
// Expected output:
// 0 | 1 | 2 | 3

draw([]);
// Expected output:
// undefined

maybe()

Returns a random boolean.

maybe();
// Expected output:
// true | false

random(min?, max?)

Returns a random value between a specified minimum and maximum value.

If the minimum and maximum values contradict each other, then this function will return NaN.

NOTE: this utility does NOT use CSPRNG.

random();
// Expected output:
// n where n > 0 and n < 1

random(10, 20);
// Expected output:
// n where n > 10 and n < 20

random(1, 0);
// Expected output:
// NaN

scatter(list, split?, options?)

Given an array, splits that array into 2 given a hard split and devides the items at random into the 2 given lists.
The split must be a number between 0 and 1. If it is not inside that range it will return a fixed sized array according to that split, so if percentage is more than or equal to 1 it will always return [list, []] and if percentage is less than or equal to 0 it will always return [[], list] (Do note that these are handled as exception cases, meaning if this is the case then the first list will not be in a random order, but preserved order instead).

NOTE: the first array will be in a random order, while the second array will have the order preserved.

scatter([0, 1, 2, 3, 4]);
// Possible output:
// [[3, 2, 4], [0, 1]]

scatter([0, 1, 2, 3, 4], 0.6);
// Possible output:
// [[3, 2, 4], [0, 1]]

scatter([0, 1, 2, 3, 4], 0.4);
// Possible output:
// [[2, 4], [0, 1, 3]]


scatter([0, 1, 2, 3, 4], 0.5, {
    bias: "FLOOR",
});
// Possible output:
// [[2, 4], [0, 1, 3]]

scatter([0, 1, 2, 3, 4], 0.5, {
    bias: "ROUND",
});
// Possible output:
// [[3, 2, 4], [0, 1]]

scatter([0, 1, 2, 3, 4], 0.5, {
    bias: "CEILING",
});
// Possible output:
// [[3, 2, 4], [0, 1]]

options:

  • bias - When the split does not work exactly for the given array length, this will decide how to split the final item (e.g. given an array of 5 items and a split of 0.5 (50%), the bias will decide if the split will be 3 - 2 or 2 - 3) (default = "ROUND")

shuffle(list)

Shuffles the array into a new array will all the items in a random order.

shuffle([0, 1, 2, 3, 4]);
// Possible output:
// [2, 4, 0, 1, 3]

uid(length?, charset?)

Returns a random string of characters gotten from a specified charset that can be used for ids.
The default length is 8 and the default charset is ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.

uid();
// Possible output:
// "Dae3pmZH"

uid(12);
// Possible output:
// "9lqD8Mp3CUrK"

uid(8, "Aa");
// Possible output:
// "AaAAAaAA"

String utilities

Casing utilities

camelCase(str, options?)

Turns a string into a camel cased version of that same string.

camelCase("Some value");
// Expected output:
// "someValue"

camelCase("someValue");
// Expected output:
// "someValue"

camelCase("some_value");
// Expected output:
// "someValue"

camelCase("some 123 value");
// Expected output:
// "some123value"

camelCase("some 123 value", { groupNumbers: true });
// Expected output:
// "some123Value"

camelCase("someUPPERValue");
// Expected output:
// "someUpperValue"

camelCase("someUPPERValue", { groupUppercaseLetters: false });
// Expected output:
// "someUPPERValue"

The options for this are inherited from customCase but without the seperator and word transformer

capitalize(str)

Converts the first character of string to uppercase.

capitalize("some value");
// Expected output:
// "Some value"
customCase(str, options)

Converts a string into a custom cased version of the string, required a seperator and word transformer to work.

NOTE:
This library also exports other casing utils that use this function under the hood and can (and most likely should) be used in most cases.

customCase("someValue", {
    seperator: ".",
    transform: (str) => str.toLowercase(),
});
// Expected output:
// "some.value"

customCase("someValue", {
    seperator: ".",
    transform: (str, index) => `${str.toLowercase()}${index}`,
});
// Expected output:
// "some0.value1"

customCase("someValue123", {
    seperator: ".",
    transform: (str) => str.toLowercase(),
});
// Expected output:
// "some.value123"

customCase("someValue123", {
    seperator: ".",
    transform: (str) => str.toLowercase(),
    groupNumbers: true,
});
// Expected output:
// "some.value.123"

customCase("HTTP", {
    seperator: ".",
    transform: (str) => str.toLowercase(),
});
// Expected output:
// "http"

customCase("HTTPServer", {
    seperator: ".",
    transform: (str) => str.toLowercase(),
});
// Expected output:
// "http.server"

customCase("HTTP", {
    seperator: ".",
    transform: (str) => str.toLowercase(),
    groupUppercaseLetters: false,
});
// Expected output:
// "h.t.t.p"

Options:

  • seperator (required) - The seperator to use when combining the words back together
  • transform (required) - a function that is given the current word + the index of that word and transforms it into a string that is then used for the output
  • groupNumbers - A flag for whether numbers should be grouped into it's own word, or if it should be appended into the current word. (default false)
  • groupUppercaseLetters - A flag for whether multiple consecutive uppercase letters are considered their own word, or part of the current word. Do note that if this is false then uppercase letters are still considered word terminators, closing the current word and starting a new one, turning HTTP into ["H", "T", "T", "P"] for example (default true)
  • parser - A function that is given the entire string and expected to parse it into the words. This is here just in case the build in parser does not satisfy your use case. If this is defined, the other options meant for parsing (groupNumbers and groupUppercaseLetters) are ignored as this function is expected to handle this behavior itself

The default word parser uses a regex to determine the characters casing and splits the given string into words, those words are by default the entire word until a new uppercase letter or spacing character (using /[\s-_]/ regex) is found. By default it tries to group all uppercase letters until a lowercase letter is found, if that is found then the character before that character is assumed to belong to new lowercase letter.

httpHeaderCase(str, options?)

Turns a string into a http header cased version of that same string.

This is also aliased to trainCase

httpHeaderCase("Some value");
// Expected output:
// "Some-Value"

httpHeaderCase("someValue");
// Expected output:
// "Some-Value"

httpHeaderCase("some_value");
// Expected output:
// "Some-Value"

httpHeaderCase("some 123 value");
// Expected output:
// "Some-123value"

httpHeaderCase("some 123 value", { groupNumbers: true });
// Expected output:
// "Some-123-Value"

httpHeaderCase("someUPPERValue");
// Expected output:
// "Some-Upper-Value"

httpHeaderCase("someUPPERValue", { groupUppercaseLetters: false });
// Expected output:
// "Some-U-P-P-E-R-Value"

The options for this are inherited from customCase but without the seperator and word transformer

kebabCase(str, options?)

Turns a string into a kebab cased version of that same string.

kebabCase("Some value");
// Expected output:
// "some-value"

kebabCase("someValue");
// Expected output:
// "some-value"

kebabCase("some_value");
// Expected output:
// "some-value"

kebabCase("some 123 value");
// Expected output:
// "some-123value"

kebabCase("some 123 value", { groupNumbers: true });
// Expected output:
// "some-123-value"

kebabCase("someUPPERValue");
// Expected output:
// "some-upper-value"

kebabCase("someUPPERValue", { groupUppercaseLetters: false });
// Expected output:
// "some-u-p-p-e-r-value"

The options for this are inherited from customCase but without the seperator and word transformer

lowerCase(str)

Converts a string to lowercase.

lowerCase("SOME VALUE");
// Expected output:
// "some value"
pascalCase(str, options?)

Turns a string into a pascal cased version of that same string.

pascalCase("Some value");
// Expected output:
// "SomeValue"

pascalCase("someValue");
// Expected output:
// "SomeValue"

pascalCase("some_value");
// Expected output:
// "SomeValue"

pascalCase("some 123 value");
// Expected output:
// "Some123value"

pascalCase("some 123 value", { groupNumbers: true });
// Expected output:
// "Some123Value"

pascalCase("someUPPERValue");
// Expected output:
// "SomeUpperValue"

pascalCase("someUPPERValue", { groupUppercaseLetters: false });
// Expected output:
// "SomeUPPERValue"

The options for this are inherited from customCase but without the seperator and word transformer

snakeCase(str, options?)

Turns a string into a snake cased version of that same string.

snakeCase("Some value");
// Expected output:
// "some_value"

snakeCase("someValue");
// Expected output:
// "some_value"

snakeCase("some-value");
// Expected output:
// "some_value"

snakeCase("some 123 value");
// Expected output:
// "some_123value"

snakeCase("some 123 value", { groupNumbers: true });
// Expected output:
// "some_123_value"

snakeCase("someUPPERValue");
// Expected output:
// "some_upper_value"

snakeCase("someUPPERValue", { groupUppercaseLetters: false });
// Expected output:
// "some_u_p_p_e_r_value"

The options for this are inherited from customCase but without the seperator and word transformer

titleCase(str, options?)

Turns a string into a title cased version of that same string.

titleCase("Some_value");
// Expected output:
// "Some Value"

titleCase("someValue");
// Expected output:
// "Some Value"

titleCase("some_value");
// Expected output:
// "Some Value"

titleCase("some 123 value");
// Expected output:
// "Some 123value"

titleCase("some 123 value", { groupNumbers: true });
// Expected output:
// "Some 123 Value"

titleCase("someUPPERValue");
// Expected output:
// "Some Upper Value"

titleCase("someUPPERValue", { groupUppercaseLetters: false });
// Expected output:
// "Some U P P E R Value"

The options for this are inherited from customCase but without the seperator and word transformer

uncapitalize(str)

Converts the first character of string to lowercase.

uncapitalize("Some value");
// Expected output:
// "some value"
upperCase(str)

Converts a string to UPPERCASE.

upperCase("some value");
// Expected output:
// "SOME VALUE"

parseUrlParams(url, transform?)

Parses the query params of a URL into an object. Optionally accepts a transform object to map each param key to a parser function, producing a typed result.

parseUrlParams("https://example.com?page=2&active=true");
// Expected output:
// {
//     page: "2",
//     active: "true"
// }

parseUrlParams("https://example.com?page=2&active=true", {
    page: toInt,
    active: (value) => value === "true",
});
// Expected output:
// {
//     page: 2,
//     active: true
// }

slug(text)

Converts a string into a URL-friendly slug.

slug("Hello, World!");
// Expected output:
// "hello-world"

textDifference(oldValue, newValue, options?)

Diffs two strings and returns either a constructed string with configurable wrapper tags around each changed part, or a list of raw diff nodes ({ type, content, context }).

Do note that the context for the diff nodes is always UNKNOWN if the htmlAware option isn't true.

Supports an HTML-aware mode that diffs markup structurally instead of as plain text: an element is only diffed on its content when its opening and closing tags are unchanged on both sides. The moment a tag itself differs (an attribute added/changed/removed, or a different element entirely) the whole element is treated as one insert/delete block instead of only the changed tag. This means the output can be used directly to render the diff.

textDifference("Hello world", "Hello there");
// Expected output:
// 'Hello <span data-diff="delete">world</span><span data-diff="insert">there</span>'

textDifference("Hello world", "Hello there", {
    raw: true,
});
// Expected output:
// [
//     { type: "EQUAL", content: "Hello ", context: "UNKNOWN" },
//     { type: "DELETE", content: "world", context: "UNKNOWN" },
//     { type: "INSERT", content: "there", context: "UNKNOWN" },
// ]

textDifference('<p class="a">Same text</p>', '<p class="b">Same text</p>', {
    htmlAware: true,
});
// Expected output:
// '<div data-diff="delete"><p class="a">Same text</p></div><div data-diff="insert"><p class="b">Same text</p></div>'
// (the attribute change pulls the entire element into the insert/delete block, instead of just the tag)

textDifference("Hello world", "Hello there", {
    tags: {
        insert: "**",
        delete: "~~",
    },
});
// Expected output:
// "Hello ~~world~~**there**"

textDifference("Hello world", "Hello there", {
    tags: {
        insert: ["<ins>", "</ins>"],
        delete: ["<del>", "</del>"],
    },
});
// Expected output:
// "Hello <del>world</del><ins>there</ins>"

textDifference("<div><p>Hello world</p></div>", "<div><p>Hello there</p><p>New paragraph</p></div>", {
    htmlAware: true,
    tags: {
        insert: ["<ins>", "</ins>"],
        delete: ["<del>", "</del>"],
    },
});
// Expected output:
// '<div><p>Hello <del>world</del><ins>there</ins></p><ins><p>New paragraph</p></ins></div>'

textDifference("<div><p>Hello world</p></div>", "<div><p>Hello there</p><p>New paragraph</p></div>", {
    htmlAware: true,
    tags: {
        inlineContext: {
            insert: ["<ins>", "</ins>"],
            delete: ["<del>", "</del>"],
        },
        blockContext: {
            insert: ['<div class="diff-insert">', "</div>"],
            delete: ['<div class="diff-delete">', "</div>"],
        },
    },
});
// Expected output:
// '<div><p>Hello <del>world</del><ins>there</ins></p><div class="diff-insert"><p>New paragraph</p></div></div>'
// (the inline text change uses inlineContext tags, the whole new paragraph uses blockContext tags)

Options:

  • htmlAware - diffs HTML structurally instead of as plain text (default false)
  • raw - when true, returns the raw list of diff nodes instead of a constructed string (default false)
  • tags - customizes the wrapper tags used around equal/insert/delete content when constructing into a string. Each can be a single string (used as both the opening and closing tag) or a [open, close] tuple. When htmlAware is true, tags can instead be split into inlineContext/blockContext to use different wrappers for inline versus block-level HTML changes.
    By default it will use no tags for equal.
    for insert it will use <span data-diff="insert"> for opening and </span> for closing (if in block context and htmlAware is true then it will use <div data-diff="insert"> for opening and </div> for closing instead).
    for delete it will use <span data-diff="delete"> for opening and </span> for closing (if in block context and htmlAware is true then it will use <div data-diff="delete"> for opening and </div> for closing instead).