@robonen/stdlib
A platform-independent standard library of tools, utilities, and helpers for TypeScript — arrays, async, math, data structures, and patterns, all tree-shakeable and fully typed.
Every project ends up reimplementing the same handful of helpers: dedupe an array, clamp a number, group records by a key, retry a flaky request. @robonen/stdlib collects those building blocks into one cohesive, dependency-free package. It runs the same in Node, the browser, and the edge — there are no platform globals, no polyfills, and no runtime dependencies. Import only what you use; the rest is shaken out of your bundle.
Fully typed
Generic signatures preserve element and key types end to end, so inference keeps working through groupBy, partition, zip, and friends.
Zero dependencies
No transitive dependencies and no platform assumptions. The same code runs in Node, the browser, Deno, Bun, and edge runtimes.
Tree-shakeable
Each utility is a standalone export with no shared side effects. Import a single function and ship only that function.
Batteries included
Beyond array and math helpers you get data structures (Deque, BinaryHeap, LinkedList) and patterns (StateMachine, PubSub, Command).
Install
pnpm add @robonen/stdlibQuick start
Import named utilities directly from the package root. Each one is small, predictable, and focused on a single job.
import { groupBy, unique, clamp, tryIt } from '@robonen/stdlib';
// Arrays — group records by a derived key
const byType = groupBy(
[{ type: 'a', v: 1 }, { type: 'b', v: 2 }, { type: 'a', v: 3 }],
item => item.type,
);
// => { a: [{ type: 'a', v: 1 }, { type: 'a', v: 3 }], b: [{ type: 'b', v: 2 }] }
// Arrays — dedupe in a single pass
unique([1, 1, 2, 3, 3]); // => [1, 2, 3]
// Math — keep a value inside a range
clamp(value, 0, 100);
// Async — error handling without forking control flow
const { error, data } = await tryIt(fetch)('/api/todos/1');
if (error) {
// handle the failure
} else {
// use data
}What's inside
The library is organized into focused modules. A few of the most-used building blocks:
- Arrays —
groupBy,partition,unique,zip,cluster,range. - Async —
tryIt,retry,pool,sleepfor control flow that doesn't fight you. - Math —
clamp,lerp,remap, each with a BigInt variant. - Functions —
debounce,throttle,memoize,once,compose,pipe. - Structs & patterns —
Deque,PriorityQueue,StateMachine,PubSuband more.
API Reference
Arrays · 14
Cluster an array into subarrays of a specific size
Returns the first element of an array
Groups the elements of an array by the key returned by `getKey`
Return a new array with `items` inserted at `index`. The index is clamped into `[0, length]`, so a too-large index appends. Never mutates.
Gets the last element of an array
Return a new array with the item at `from` moved to `to`. Out-of-range `from` returns a shallow copy unchanged; `to` is clamped into range. Never mutates.
Splits an array into two: elements that satisfy the predicate and those that do not
Generates an array of numbers from `start` (inclusive) to `stop` (exclusive)
Return a new array with the item at `index` removed. Returns a shallow copy unchanged when the index is out of range. Never mutates.
Returns the sum of all the elements in an array
Return a new array with the items at indices `a` and `b` swapped. Returns a shallow copy unchanged when either index is out of range or equal. Never mutates.
Normalize an `Arrayable<T>` value into an array. `undefined` and `null` become an empty array; a single value is wrapped; arrays are returned as-is (no copy).
Returns a new array with unique values from the original array
Combines several arrays into an array of tuples, stopping at the shortest input
Async · 4
A concurrency-limited async task pool with AbortSignal support. Tasks start immediately when under the concurrency limit and are queued otherwise. Each task receives the pool's AbortSignal for cooperative cancellation. Use `all()` to wait for all tasks (throws AggregateError on any failure) or `allSettled()` to inspect individual results — mirroring the Promise static API.
Retries a function a specified number of times with a delay between each retry
Delays the execution of the current function by the specified amount of time
Wraps promise-based code in a try/catch block without forking the control flow
Bits · 9
Function to combine multiple flags using the AND operator
A bit vector is a vector of bits that can be used to store a collection of bits
Create a function that generates unique flags
Function to make sure a flag has a specific bit set
Function to check if a flag is set
Function to apply the bitwise NOT (complement) operator to a flag
Function to combine multiple flags using the OR operator
Function to toggle (xor) a flag
Function to unset a flag
Collections · 2
Safely read a deeply nested value from a collection by a dot-separated path
Write a deeply nested value into a collection by a dot-separated path, creating any missing intermediate containers along the way. A numeric next segment creates an array, otherwise an object. Mutates and returns the original collection.
Comparators · 1
Functions · 6
Composes functions right-to-left: `compose(f, g)(x)` is `f(g(x))`
Delays invoking a function until `wait` ms have elapsed since the last call
Caches the result of a function by its arguments
Wraps a function so it runs at most once; subsequent calls return the first result
Composes functions left-to-right: `pipe(f, g)(x)` is `g(f(x))`
Invokes a function at most once per `wait` ms
Math · 10
Clamps a number between a minimum and maximum value
Clamps a bigint between a minimum and maximum value
Inverse linear interpolation between two values
Inverse linear interpolation between two bigint values
Linearly interpolates between two values
Linearly interpolates between bigint values
Like `Math.max` but for BigInts
Like `Math.min` but for BigInts
Map a value from one range to another
Map a bigint value from one range to another
Objects · 2
Patterns · 7
Async command history with undo/redo/batch support
Async finite state machine with support for async guards, actions, and hooks
Command history with undo/redo/batch support
Create a type-safe async finite state machine with context
Create a type-safe synchronous finite state machine with context
Simple PubSub implementation
Simple, performant, and type-safe finite state machine
Structs · 7
Binary heap backed by a flat array with configurable comparator
A circular (ring) buffer with automatic growth, O(1) push/pop on both ends
Represents a double-ended queue backed by a circular buffer
Doubly linked list with O(1) push/pop on both ends and O(1) insert/remove by node reference
Priority queue backed by a binary heap with configurable comparator and optional max size
Represents a queue data structure (FIFO) backed by a Deque
Represents a stack data structure
Sync · 1
Text · 9
Removes the placeholder syntax from a template string.
Extracts all placeholders from a template string.
Generates a type for a template string with placeholders.
Calculate the Levenshtein distance between two strings
Type of a fallback value when a template key is not found.
Replace `{path}` placeholders in a template string with values resolved from `args` by dot-path. Placeholder keys are inferred from the template, so `args` is type-checked and auto-completed against them.
Type of a value that will be used to replace a placeholder in a template.
Calculates the trigram distance between two strings
Extracts trigrams from a text and returns a map of trigram to count
Types · 14
Any function
A type that can be either a single value or an array of values
A collection definition
Check if `S` has any spaces
Represents a value that may be a promise.
Parse a collection path string into an array of keys
Like {@link PathToType}, but every object key is optional and objects stay open (accept extra keys). Useful when the produced type only describes the keys a consumer *may* provide rather than the full shape of the source data.
Convert a collection path array into a Target type
A type that can be either a single value or a readonly array of values
Stringable type
Trim leading and trailing whitespace from `S`
Convert a union type to an intersection type
Void function
Whitespace characters recognized by {@link Trim}