- Install:
npm install metautil - Require:
const metautil = require('metautil')
toBool = [() => true, () => false]- Example:
const created = await mkdir(path).then(...toBool);
- Example:
timeout(msec: number, signal?: AbortSignal): Promise<void>delay(msec: number, signal?: AbortSignal): Promise<void>timeoutify(promise: Promise<unknown>, msec: number): Promise<unknown>collect(keys: Array<string>, options?: CollectorOptions): Collectoroptions.exact?: booleanoptions.timeout?: numberoptions.reassign?: boolean
Async collection is an utility to collect needed keys and signalize on done.
constructor(keys: Array<string>, options?: CollectorOptions)options.exact?: booleanoptions.timeout?: numberoptions.reassign?: booleanoptions.defaults?: objectoptions.validate?: (data: Record<string, unknown>) => unknown
set(key: string, value: unknown): voidwait(key: string, fn: AsyncFunction | Promise<unknown>, ...args?: Array<unknown>): voidtake(key: string, fn: Function, ...args?: Array<unknown>): voidcollect(sources: Record<string, Collector>): voidfail(error: Error): voidabort(): voidthen(onFulfilled: Function, onRejected?: Function): Promise<unknown>done: booleandata: Dictionarykeys: Array<string>count: numberexact: booleantimeout: numberdefaults: objectreassign: booleanvalidate?: (data: Record<string, unknown>) => unknownsignal: AbortSignal
Collect keys with .set method:
const ac = collect(['userName', 'fileName']);
setTimeout(() => ac.set('fileName', 'marcus.txt'), 100);
setTimeout(() => ac.set('userName', 'Marcus'), 200);
const result = await ac;
console.log(result);Collect keys with .wait method from async or promise-returning function:
const ac = collect(['user', 'file']);
ac.wait('file', getFilePromisified, 'marcus.txt');
ac.wait('user', getUserPromisified, 'Marcus');
try {
const result = await ac;
console.log(result);
} catch (error) {
console.error(error);
}Collect keys with .take method from callback-last-error-first function:
const ac = collect(['user', 'file'], { timeout: 2000, exact: false });
ac.take('file', getFileCallback, 'marcus.txt');
ac.take('user', getUserCallback, 'Marcus');
const result = await ac;Set default values โโfor unset keys using the options.defaults argument:
const defaults = { key1: 'sub1', key2: 'sub1' };
const dc = collect(['key1', 'key2'], { defaults, timeout: 2000 });
dc.set('key2', 'sub2');
const result = await dc;Compose collectors (collect subkeys from multiple sources):
const dc = collect(['key1', 'key2', 'key3']);
const key1 = collect(['sub1']);
const key3 = collect(['sub3']);
dc.collect({ key1, key3 });
const result = await dc;Complex example: compare Promise.allSettled + Promise.race vs Collector in next two examples:
// Collect 4 keys from different contracts with Promise.allSettled + Promise.race
const promise1 = new Promise((resolve, reject) => {
fs.readFile('README.md', (err, data) => {
if (err) return void reject(err);
resolve(data);
});
});
const promise2 = fs.promises.readFile('README.md');
const url = 'http://worldtimeapi.org/api/timezone/Europe';
const promise3 = fetch(url).then((data) => data.json());
const promise4 = new Promise((resolve) => {
setTimeout(() => resolve('value4'), 50);
});
const timeout = new Promise((resolve, reject) => {
setTimeout(() => reject(new Error('Timed out')), 1000);
});
const data = Promise.allSettled([promise1, promise2, promise3, promise4]);
try {
const keys = await Promise.race([data, timeout]);
const [key1, key2, key3, key4] = keys.map(({ value }) => value);
const result = { key1, key2, key3, key4 };
console.log(result);
} catch (err) {
console.log(err);
}Compare with:
// Collect 4 keys from different contracts with Collector
const dc = collect(['key1', 'key2', 'key3', 'key4'], { timeout: 1000 });
dc.take('key1', fs.readFile, 'README.md');
dc.wait('key2', fs.promises.readFile, 'README.md');
const url = 'http://worldtimeapi.org/api/timezone/Europe';
dc.wait(
'key3',
fetch(url).then((data) => data.json()),
);
setTimeout(() => dc.set('key4', 'value4'), 50);
try {
const result = await dc;
console.log(result);
} catch (err) {
console.log(err);
}cryptoRandom(min?: number, max?: number): numberrandom(min?: number, max?: number): numbergenerateUUID(): stringgenerateKey(possible: string, length: number): stringcrcToken(secret: string, key: string): stringgenerateToken(secret: string, characters: string, length: number): stringvalidateToken(secret: string, token: string): booleanserializeHash(hash: Buffer, salt: Buffer): stringdeserializeHash(phcString: string): HashInfohashPassword(password: string): Promise<string>validatePassword(password: string, serHash: string): Promise<boolean>md5(fileName: string): Promise<string>getX509names(cert: X509Certificate): Strings
const x509 = new crypto.X509Certificate(cert);
const domains = getX509names(x509);duration(s: string | number): numbernowDate(date?: Date): stringnowDateTimeUTC(date?: Date, timeSep?: string): stringparseMonth(s: string): numberparseDay(s: string): numberparseEvery(s: string): EverynextEvent(every: Every, date?: Date): number
- Class
Errorconstructor(message: string, options?: number | string | ErrorOptions)options.code?: number | stringoptions.cause?: Error
message: stringstack: stringcode?: number | stringcause?: Error
- Class
DomainErrorconstructor(code?: string, options?: number | string | ErrorOptions)options.code?: number | stringoptions.cause?: Error
message: stringstack: stringcode?: number | stringcause?: ErrortoError(errors: Errors): Error
isError(instance: object): boolean
A container holding either a value or an error, useful to avoid try/catch
boilerplate and to pass either outcome around as a single value.
constructor(value?: unknown, error?: unknown)static ok(value?: unknown): Resultstatic fail(error: unknown): Resultstatic from(fn: () => unknown): Resultstatic fromAsync(fn: () => Promise<unknown>): Promise<Result>value: unknownerror: unknownok: booleanunwrap(defaultValue?: unknown): unknownmap(fn: (value: unknown) => unknown): Result
const parsed = Result.from(() => JSON.parse(input));
if (parsed.ok) console.log(parsed.value);
else console.error(parsed.error);
const loaded = await Result.fromAsync(() => readFile(path));
const size = loaded.map((buffer) => buffer.length).unwrap(0);exists(path: string): Promise<boolean>directoryExists(path: string): Promise<boolean>fileExists(path: string): Promise<boolean>ensureDirectory(path: string): Promise<boolean>parsePath(relPath: string): Strings
parseHost(host?: string): stringparseParams(params: string): CookiesparseCookies(cookie: string): HeadersparseRange(range: string): StreamRange
- Deprecated in 4.x:
fetch(url: string, options?: FetchOptions): Promise<Response> receiveBody(stream: IncomingMessage): Promise<Buffer | null>ipToInt(ip?: string): numberintToIp(int: number): stringhttpApiCall(url: string, options: ApiOptions): Promise<object>options.method?: HttpMethodoptions.headers?: objectoptions.body?: Body
makePrivate(instance: object): objectprotect(allowMixins: Strings, ...namespaces: Namespaces): voidjsonParse(data: Buffer | string | null | undefined): Dictionary | nullisHashObject(o: string | number | boolean | object): booleanflatObject(source: Dictionary, fields: Strings): DictionaryunflatObject(source: Dictionary, fields: Strings): DictionarygetSignature(method: Function): StringsnamespaceByPath(namespace: Dictionary, path: string): Dictionary | nullserializeArguments(fields: Strings, args: Dictionary): stringfirstKey(obj: Dictionary): string | undefinedisInstanceOf(obj: unknown, constrName: string): booleancons(value: unknown, next?: unknown): Cons
Immutable pair cell (linked-list node shape) with private fields.
For a sized immutable list ADT with prepend / rest / iteration, see
ConsList.
constructor(value: unknown, next?: unknown)โnextdefaults tonullvalue: unknownโ read-only headnext: unknownโ read-only tail (nullor anotherCons)static value(pair: Cons): unknownstatic next(pair: Cons): unknown
const { cons, Cons } = metautil;
const list = cons(1, cons(2, cons(3, null)));
console.log(list.value); // 1
console.log(Cons.next(list).value); // 2
console.log(Cons.value(Cons.next(Cons.next(list)))); // 3Typed records with schema inferred from literal defaults.
Struct.immutable(className: string, defaults: object): StructClassStruct.mutable(className: string, defaults: object): StructClass
Default literals define field types:
undefinedโ schemaunknown, accepts any value, defaults toundefinednullโ schemaref, accepts null, objects, and functions, defaults tonull[]โ schemaarray, accepts arrays, fresh copy per instance{}โ schemaobject, accepts plain objects, fresh copy per instance- primitive โ schema
typeof, accepts exact primitive type, literal default value
Generated class:
constructor(data?: object)static create(data?: object): StructRecordstatic fields: Array<string>static schema: objectstatic mutable: booleanupdate(updates: object): this(mutable only)fork(updates?: object): StructRecordbranch(updates?: object): StructRecordtoObject(): object
const City = metautil.Struct.immutable('City', { name: 'Unknown' });
const rome = new City({ name: 'Rome' });
const User = metautil.Struct.mutable('User', {
id: 0,
name: 'Anonymous',
roles: [],
});
const marcus = User.create({ id: 1, name: 'Marcus' });constructor(options: PoolOptions)options.timeout?: number
items: Array<unknown>free: Array<boolean>queue: Array<unknown>current: numbersize: numberavailable: numbertimeout: numbernext(exclusive?: boolean): Promise<unknown>add(item: unknown): voidcapture(): Promise<unknown>release(item: unknown): voidisFree(item: unknown): boolean
const pool = new Pool();
pool.add({ a: 1 });
pool.add({ a: 2 });
pool.add({ a: 3 });
if (pool.isFree(obj1)) console.log('1 is free');
const item = await pool.capture();
if (pool.isFree(obj1)) console.log('1 is captured');
const obj = await pool.next();
// obj is { a: 2 }
pool.release(item);All data structure classes implement a common interoperability contract:
every class has static fromArray, static fromIterable, toArray,
and [Symbol.iterator], making any structure convertible to any other
via Array as the universal interchange format. The shared TypeScript
interfaces Sequence<T> and Indexable<T> (in metautil.d.ts) describe
structural contracts at the type level. Stack and Queue are thin
ADT facades over Deque (same circular buffer; flavored method names).
List is a value-level facade over an internal doubly-linked list.
ConsList is a separate immutable cons ADT (not the same as pair cell
Cons).
| Class | ADT | Backed by | Ends | Index |
|---|---|---|---|---|
Deque |
double-ended | circular buffer | O(1) | O(1) |
Queue |
FIFO | Deque |
O(1) | โ |
Stack |
LIFO | Deque |
O(1) | โ |
List |
sequence | doubly-linked | O(1) | O(n) |
ConsList |
immutable cons | shared nodes | O(1) | O(n) |
// Any structure can feed any other via iterables
const list = List.range(1, 5);
const queue = Queue.fromIterable(list.filter((n) => n % 2 === 0));
const deque = Deque.fromIterable(queue);
const cons = ConsList.fromArray(deque.toArray());An immutable singly-linked cons-list with structural sharing (distinct
from the Cons pair cell). Every prepend returns a new ConsList
that shares its tail with the original โ enabling multiple independent
branches from a common suffix at zero copy cost (inspired by LISP cons
cells).
static empty: ConsList<any>โ canonical empty singletonstatic of<T>(...values: Array<T>): ConsList<T>static fromArray<T>(values: Array<T>): ConsList<T>static fromIterable<T>(iterable: Iterable<T>): ConsList<T>prepend(value: T): ConsList<T>โ O(1), returns new head sharing old tailfirst(): T | undefinedโ head valuerest(): ConsList<T>โ tail (O(1), no copy;emptywhen none)toArray(): Array<T>[Symbol.iterator](): IterableIterator<T>value: T | undefinednext: ConsList<T> | nullsize: numberisEmpty(): boolean
const shared = ConsList.of(3, 4, 5);
const branch1 = shared.prepend(2).prepend(1); // [1, 2, 3, 4, 5]
const branch2 = shared.prepend(99); // [99, 3, 4, 5]
// Both branches share the [3, 4, 5] suffix โ no copying
console.log(branch1.next.next === shared); // true
console.log(branch2.next === shared); // trueUse case: undo history with branching (time-travel state)
let history = ConsList.of('draft v1');
history = history.prepend('draft v2');
history = history.prepend('draft v3');
console.log(history.first()); // 'draft v3'
// Jump back in time โ earlier states remain valid and untouched
const undone = history.rest();
console.log(undone.first()); // 'draft v2'
// Branch a new edit off the older state without affecting `history`
const branched = undone.prepend('draft v2b');
console.log(branched.toArray()); // ['draft v2b', 'draft v2', 'draft v1']
console.log(history.toArray()); // ['draft v3', 'draft v2', 'draft v1']A doubly-linked-list-backed sequence with a comprehensive API. All push/pop/append/prepend operations are O(1); index-based operations are O(n).
Construction
constructor()static fromArray<T>(values: Array<T>): List<T>static fromIterable<T>(iterable: Iterable<T>): List<T>static range(start: number, end: number, step?: number): List<number>static merge<T>(lists: Array<List<T>>): List<T>
CRUD / index
append(value: T): voidprepend(value: T): voidenqueue(value: T): voidโ alias forappenddequeue(): T | undefinedโ removes and returns first elementinsert(index: number, value: T, count?: number): voiddelete(index: number, count?: number): voidat(index: number): T | undefinedset(index: number, value: T): voidfirst(): T | undefinedlast(): T | undefined
Slicing
tail(n?: number): List<T>โ all-but-first-n (default 1)init(n?: number): List<T>โ all-but-last-n (default 1)drop(n: number): voidโ drops first n (or last |n| if negative)take(n: number): List<T>โ first n (or last |n| if negative)slice(start?: number, end?: number): List<T>
Rearranging
rotateLeft(steps?: number): voidrotateRight(steps?: number): voidrotate(n: number): voidโ positive rotates left, negative rightswap(i: number, j: number): voidmove(from: number, to: number): voidsplitAt(index: number): { before: List<T>; after: List<T> }groupBy<K>(key: (v: T) => K): Map<K, List<T>>
Search / compare
includes(value: T): booleanindexOf(value: T): numberlastIndexOf(value: T): numberequals(other: List<T>): boolean
Bulk mutations
addAll(values: Iterable<T>): voidremoveAll(values: Iterable<T>): voidfill(value: T, start?: number, end?: number): voidreplace(oldValue: T, newValue: T): voiddistinct(): voidโ removes duplicates in placetoDistinct(): List<T>
Ordering
shuffle(): voidtoShuffled(): List<T>reverse(): voidtoReversed(): List<T>sort(compare?: (a: T, b: T) => number): voidtoSorted(compare?: (a: T, b: T) => number): List<T>
Functional
map<U>(fn: (value: T, index: number) => U): List<U>lazyMap<U>(fn): IterableIterator<U>โ lazy, does not materializeflatMap<U>(fn: (value: T) => Iterable<U>): List<U>filter(fn: (value: T, index: number) => boolean): List<T>lazyFilter(fn): IterableIterator<T>โ lazy, does not materializereduce<U>(fn, initial: U): UlazyReduce<U>(fn, initial: U): IterableIterator<U>โ running accumulator (scan)some(fn): booleanevery(fn): booleanfind(fn): T | undefinedfindIndex(fn): number
Stats
sum(fn?: (value: T) => number): numberavg(fn?: (value: T) => number): numbermin(compare?: (a: T, b: T) => number): T | undefinedmax(compare?: (a: T, b: T) => number): T | undefined
Utility
isEmpty(): booleanclear(): voidtoArray(): Array<T>join(separator?: string): stringclone(): List<T>[Symbol.iterator](): IterableIterator<T>[Symbol.asyncIterator](): AsyncIterableIterator<T>size: number
const list = List.range(1, 5);
list.append(6);
list.prepend(0);
console.log(list.toArray()); // [0, 1, 2, 3, 4, 5, 6]
console.log(list.filter((v) => v % 2 === 0).toArray()); // [0, 2, 4, 6]
console.log(list.reduce((acc, v) => acc + v, 0)); // 21
const grouped = list.groupBy((v) => v % 3);
console.log(grouped.get(0).toArray()); // [0, 3, 6]Use case: playlist manager
const playlist = List.fromArray(['intro', 'verse', 'chorus', 'verse', 'outro']);
playlist.distinct(); // drop duplicate tracks in place
console.log(playlist.toArray()); // ['intro', 'verse', 'chorus', 'outro']
playlist.move(3, 0); // move 'outro' to the front
console.log(playlist.toArray()); // ['outro', 'intro', 'verse', 'chorus']
console.log(playlist.find((track) => track.startsWith('ch'))); // 'chorus'Double-ended queue backed by a growable circular buffer โ the shared
engine for Stack and Queue. Supports O(1) ops at both ends and O(1)
index-based access. Method names stay end-oriented (prepend / append
/ dequeue / pop).
constructor()static fromArray<T>(values: Array<T>): Deque<T>static fromIterable<T>(iterable: Iterable<T>): Deque<T>static range(start: number, end: number, step?: number): Deque<number>prepend(value: T): voidappend(value: T): voiddequeue(): T | undefinedโ removes and returns the front elementpop(): T | undefinedโ removes and returns the back elementat(index: number): T | undefinedset(index: number, value: T): voidfirst(): T | undefinedlast(): T | undefinedisEmpty(): booleanincludes(value: T): booleanequals(other: Deque<T>): booleanrotateLeft(steps?: number): voidrotateRight(steps?: number): voidclear(): voidtoArray(): Array<T>clone(): Deque<T>[Symbol.iterator](): IterableIterator<T>[Symbol.asyncIterator](): AsyncIterableIterator<T>size: number
const deque = Deque.range(1, 5);
// [1, 2, 3, 4, 5]
deque.prepend(0);
deque.append(6);
console.log(deque.dequeue()); // 0
console.log(deque.pop()); // 6
deque.rotateLeft(2);
console.log(deque.toArray()); // [3, 4, 5, 1, 2]Use case: sliding window maximum
// Monotonic deque of indices โ the front always holds the current max
function maxSlidingWindow(nums, k) {
const deque = new Deque();
const result = [];
for (let i = 0; i < nums.length; i++) {
if (!deque.isEmpty() && deque.first() <= i - k) deque.dequeue();
while (!deque.isEmpty() && nums[deque.last()] <= nums[i]) deque.pop();
deque.append(i);
if (i >= k - 1) result.push(nums[deque.first()]);
}
return result;
}
console.log(maxSlidingWindow([1, 3, -1, -3, 5, 3, 6, 7], 3));
// [3, 3, 5, 5, 6, 7]FIFO (first in, first out) facade over Deque: enqueue appends at the
back, dequeue / peek operate at the front. Same circular buffer and
O(1) costs as Deque.
constructor()static fromArray<T>(values: Array<T>): Queue<T>static fromIterable<T>(iterable: Iterable<T>): Queue<T>enqueue(value: T): voidโ appends at the backdequeue(): T | undefinedโ removes and returns the frontpeek(): T | undefinedโ front element (first), does not removefirst(): T | undefinedlast(): T | undefinedisEmpty(): booleanincludes(value: T): booleanclear(): voidtoArray(): Array<T>clone(): Queue<T>[Symbol.iterator](): IterableIterator<T>โ delegates toDeque[Symbol.asyncIterator](): AsyncIterableIterator<T>โ delegates toDequesize: number
const queue = new Queue();
queue.enqueue('a');
queue.enqueue('b');
queue.enqueue('c');
console.log(queue.dequeue()); // 'a'
console.log(queue.peek()); // 'b'
console.log(queue.size); // 2Use case: breadth-first traversal
const tree = {
value: 1,
children: [
{ value: 2, children: [{ value: 4, children: [] }] },
{ value: 3, children: [] },
],
};
const queue = new Queue();
queue.enqueue(tree);
const order = [];
while (!queue.isEmpty()) {
const node = queue.dequeue();
order.push(node.value);
for (const child of node.children) queue.enqueue(child);
}
console.log(order); // [1, 2, 3, 4]LIFO (last in, first out) facade over Deque: push / pop / peek
operate at the back. Same circular buffer and O(1) end costs as Deque.
constructor()static fromArray<T>(values: Array<T>): Stack<T>static fromIterable<T>(iterable: Iterable<T>): Stack<T>push(value: T): voidโ appends at the backpop(): T | undefinedโ removes and returns the backpeek(): T | undefinedโ back element (last), does not removefirst(): T | undefinedโ bottom (oldest)last(): T | undefinedโ top (same aspeek)isEmpty(): booleanincludes(value: T): booleanclear(): voidtoArray(): Array<T>clone(): Stack<T>[Symbol.iterator](): IterableIterator<T>โ delegates toDeque[Symbol.asyncIterator](): AsyncIterableIterator<T>โ delegates toDequesize: number
const stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
console.log(stack.peek()); // 3
console.log(stack.pop()); // 3
console.log(stack.size); // 2Use case: balanced brackets validator
function isBalanced(input) {
const pairs = { ')': '(', ']': '[', '}': '{' };
const stack = new Stack();
for (const char of input) {
if ('([{'.includes(char)) stack.push(char);
else if (char in pairs && stack.pop() !== pairs[char]) return false;
}
return stack.isEmpty();
}
console.log(isBalanced('{[()]}')); // true
console.log(isBalanced('{[(])}')); // falseconst cards = ['๐ก', '๐', '๐ฎ', '๐ท', '๐'];
const card = sample(cards);const players = [{ id: 10 }, { id: 12 }, { id: 15 }];
const places = shuffle(players);const player = { name: 'Marcus', score: 1500, socket };
const playerState = projection(player, ['name', 'score']);constructor(options: SemaphoreOptions)options.concurrency: numberoptions.size?: numberoptions.timeout?: number
concurrency: numbercounter: numbertimeout: numbersize: numberempty: booleanqueue: Array<QueueElement>enter(): Promise<void>leave(): void
const options = { concurrency: 3, size: 4, timeout: 1500 };
const semaphore = new Semaphore(options);
await semaphore.enter();
// Do something
semaphore.leave();replace(str: string, substr: string, newstr: string): stringbetween(s: string, prefix: string, suffix: string): stringsplit(s: string, separator: string): [string, string]isFirstUpper(s: string): booleanisFirstLower(s: string): booleanisFirstLetter(s: string): booleantoLowerCamel(s: string): stringtoUpperCamel(s: string): stringtoLower(s: string): stringtoCamel(separator: string): (s: string) => stringspinalToCamel(s: string): stringsnakeToCamel(s: string): stringisConstant(s: string): booleanfileExt(fileName: string): stringparsePath(relPath: string): StringstrimLines(s: string): string
bytesToSize(bytes: number): stringsizeToBytes(size: string): number
const size = bytesToSize(100000000);
const bytes = sizeToBytes(size);
console.log({ size, bytes });
// { size: '100 MB', bytes: 100000000 }| Symbol | zeros | Unit |
|---|---|---|
| yb | 24 | yottabyte |
| zb | 21 | zettabyte |
| eb | 18 | exabyte |
| pb | 15 | petabyte |
| tb | 12 | terabyte |
| gb | 9 | gigabyte |
| mb | 6 | megabyte |
| kb | 3 | kilobyte |
- Events:
constructor(options?: { maxListeners?: number })emit(eventName: EventName, data: unknown): Promise<void>on(eventName: EventName, listener: Listener): voidonce(eventName: EventName, listener: Listener): voidoff(eventName: EventName, listener?: Listener): void
- Adapters:
toPromise(eventName: EventName): Promise<unknown>toAsyncIterable(eventName: EventName): AsyncIterable<unknown>
- Utilities:
clear(eventName?: EventName): voidlisteners(eventName?: EventName): Listener[]listenerCount(eventName?: EventName): numbereventNames(): EventName[]
Examples:
const ee = new Emitter();
ee.on('eventA', (data) => {
console.log({ data });
// Prints: { data: 'value' }
});
ee.emit('eventA', 'value');const ee = new Emitter();
setTimeout(() => {
ee.emit('eventA', 'value');
}, 100);
const result = await ee.toPromise('eventA');const ee = new Emitter();
passReferenceSomewhere(ee);
const iterable = ee.toAsyncIterable('eventB');
for await (const eventData of iterable) {
console.log({ eventData });
}Copyright (c) 2017-2026 Metarhia contributors.
Metautil is MIT licensed.
Metautil is a part of Metarhia technology stack.