nexus-utils

A lightweight utility toolkit for Node.js and TypeScript projects.


Keywords
utility, typescript
License
ISC
Install
npm install nexus-utils@1.3.2

Documentation

toolkit

A small, framework‑agnostic utility toolkit for everyday JavaScript/TypeScript work.
Includes string/array/number/object helpers, async utilities, date helpers, a structured logger, and basic data structures (queue, stack, priority queue).

import * as nexus from 'toolkit';
import { Queue } from 'toolkit/queue';
import { Stack } from 'toolkit/stack';
import { PriorityQueue } from 'toolkit/priority-queue';
import { createClient, buildQuery, withAbort } from 'toolkit';

Installation

npm install toolkit

String utilities

Source: src/utils/string.ts

  • trim(text) – safely trims, treating null/undefined as ''.
  • toLower(text) / toUpper(text) – lower/upper‑case after trimming.
  • isEmpty(text)true if empty or only whitespace.
  • capitalize(text)"hello WORLD""Hello world".
  • slug(text) – URL‑friendly slug, "Hello World!""hello-world".
  • includes(text, search) – safe wrapper around String.prototype.includes.
  • startsWith(text, prefix) – safe wrapper around startsWith.
  • endsWith(text, suffix) – safe wrapper around endsWith.
  • words(text) – splits on whitespace, collapsing multiples.
trim('  hi  ');                // 'hi'
capitalize('hELLO');           // 'Hello'
slug('Hello World!');          // 'hello-world'

Number utilities

Source: src/utils/number.ts

  • clamp(value, min, max) – clamps into [min, max] (NaN → min).
  • toNumber(value, fallback?) – safe Number() with fallback.
  • between(value, min, max) – inclusive range check.
  • round(value, decimals?) – round to N decimals.
  • floor(value, decimals?) – floor to N decimals.
  • ceil(value, decimals?) – ceil to N decimals.
  • randomInt(min, max) – random integer in [min, max].
  • sum(numbers) – sum of an array.
  • avg(numbers) – average, 0 for empty.
clamp(15, 0, 10);      // 10
between(5, 0, 10);     // true
round(1.2345, 2);      // 1.23
randomInt(1, 6);       // 1..6
avg([1, 2, 3, 4]);     // 2.5

Array utilities

Source: src/utils/array.ts

  • uniq(items) – unique items, first occurrence wins.
  • chunk(items, size) – splits into chunks.
  • compact(items) – removes null/undefined/false (keeps 0 and '').
  • flat(items) – flattens one level.
  • first(items) / last(items) – first/last item or undefined.
  • groupBy(objects, key) – group array of objects by a key.
  • partition(items, predicate)[matches, nonMatches].
  • intersect(a, b) – items in both arrays.
  • difference(a, b) – items in a that are not in b.
  • uniqueBy(items, keyFn) – unique items by computed key.
  • sortBy(items, selector, direction?) – returns a new array sorted by a selector ('asc'/'desc', default 'asc').
uniq([1, 2, 2, 3]);  // [1, 2, 3]
chunk([1, 2, 3, 4, 5], 2); // [[1,2],[3,4],[5]]

const users = [
  { id: 1, role: 'admin' },
  { id: 2, role: 'user' },
  { id: 3, role: 'admin' },
];

groupBy(users, 'role');
// { admin: [...], user: [...] }

partition([1,2,3,4], n => n % 2 === 0);
// [[2,4],[1,3]]

sortBy(users, u => u.age);
sortBy(users, u => u.name.toLowerCase(), 'desc');

Object utilities

Source: src/utils/object.ts

  • merge(a, b) – shallow merge, b overrides a.
  • get(obj, path, fallback?) – safe deep property access ('a.b.c').
  • isEmptyObject(value) – own enumerable keys length is 0.
  • pick(obj, keys) – new object with only selected keys.
  • omit(obj, keys) – new object without selected keys.
  • keys(obj) – typed keys array.
  • values(obj) – typed values array.
merge({ a: 1, b: 2 }, { b: 3 }); // { a:1, b:3 }
get({ a: { b: 1 } }, 'a.b');     // 1
pick(user, ['id', 'name']);
omit(user, ['password']);

Async utilities

Source: src/utils/async.ts

  • sleep(ms) – Promise that resolves after ms.
  • handlePromise(fn) – wraps any async function and returns { success, data, error }, auto-unwrapping .data when present (e.g. axios).
  • timeout(promise, ms) – reject if promise doesn’t settle in ms.
  • debounce(fn, delay) – debounced function wrapper.
  • throttle(fn, interval) – throttled function wrapper.
await sleep(500);

const usersResult = await handlePromise(() =>
  axios.get('/api/users')
);
// usersResult.data is axiosResponse.data

const onSearch = debounce(q => doSearch(q), 300);
const onScroll = throttle(() => console.log('scroll'), 100);

HTTP / API utilities

Source: src/http.ts

  • buildQuery(params) – builds a query string from a flat object.
  • withAbort() – returns { signal, abort } using AbortController.
  • createClient(options) – creates a small HTTP client on top of fetch + handlePromise.
import { createClient } from 'toolkit';

const api = createClient({
  baseUrl: 'https://api.example.com',
  headers: { 'X-App': 'toolkit' },
  getAuthToken: () => localStorage.getItem('token')
});

// GET /users?active=true
const users = await api.get('/users', {
  query: { active: true }
});

// POST /users with JSON body
const newUser = await api.post('/users', { name: 'Alice' });

Date utilities

Source: src/utils/date.ts

  • now()new Date().
  • nowIso() / utcIso() – ISO time in UTC.
  • formatDate(date, format) – formats a date using preset formats like 'yyyy-MM-dd', 'yyyy-MM-dd HH:mm:ss', 'MM/dd/yyyy', etc.
  • formatUtc(date, options?) – formatted UTC string.
  • formatTz(date, timeZone, options?) – formatted string for IANA timezone, e.g. "Asia/Kolkata".
  • addDays(date, days), addMonths(date, months), addYears(date, years).
  • getYear(date), getMonth(date) (1–12), getDaysInMonth(date).
  • getTodayDate() – today's date in YYYY-MM-DD format (UTC).
  • getYesterdayDate() – yesterday's date in YYYY-MM-DD format (UTC).
  • startOfDay(date) – midnight for that day.
  • isBefore(a, b) – true if a < b.
utcIso(); // "2026-02-19T13:30:00.000Z"
formatDate(new Date(), 'yyyy-MM-dd'); // "2026-02-19"
formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss'); // "2026-02-19 14:30:45"
formatDate(new Date(), 'MM/dd/yyyy'); // "02/19/2026"
formatTz(new Date(), 'Asia/Kolkata');
addMonths(new Date(), 1);
getDaysInMonth(new Date());
getTodayDate(); // "2026-02-19"

JSON utilities

Source: src/utils/json.ts

  • parseJson(text) – safe JSON.parse, returns undefined on error.
  • stringifyJson(value, replacer?, space?) – safe JSON.stringify, returns undefined on error.
parseJson('{"a":1}');   // { a:1 }
parseJson('{bad}');     // undefined
stringifyJson({ a: 1 }); // '{"a":1}'

CSV utilities

Source: src/utils/csv.ts

  • escapeCsv(value) – escapes a single value for use in a CSV cell (quotes, commas, newlines).
  • convertToCsv(data, headers) – converts an array of objects to a CSV string with labeled headers.
const data = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' }
];

const headers = [
  { key: 'id', label: 'ID' },
  { key: 'name', label: 'Name' }
];

const csv = convertToCsv(data, headers);
// ID,Name\r\n1,Alice\r\n2,Bob\r\n

Comparison utilities

Source: src/utils/compare.ts

Safely compares any two values, handling numbers, strings, objects, and mixed types.

  • compare(a, b, key?) – returns -1 if a < b, 0 if a === b, 1 if a > b.
  • isEqual(a, b, key?) / eq(a, b, key?) – safely checks if two values are equal.
  • isLessThan(a, b, key?) / lt(a, b, key?) – checks if a < b.
  • isGreaterThan(a, b, key?) / gt(a, b, key?) – checks if a > b.
  • isLessThanOrEqual(a, b, key?) / lte(a, b, key?) – checks if a <= b.
  • isGreaterThanOrEqual(a, b, key?) / gte(a, b, key?) – checks if a >= b.

The key parameter can be a property name or a function to extract the value to compare from objects.

compare(5, 10); // -1
compare('apple', 'banana'); // -1
compare('5', 5); // 0 (coerced)

const users = [
  { id: 1, age: 25 },
  { id: 2, age: 30 }
];

compare(users[0], users[1], 'age'); // -1
eq(users[0], users[1], u => u.age); // false
lt({ value: 5 }, { value: 10 }, 'value'); // true
gt(10, 5); // true
lte(5, 5); // true
gte(10, 5); // true

ID utility

Source: src/utils/id.ts

  • id(length = 16) – random alphanumeric ID, using crypto.getRandomValues when available, otherwise Math.random.
id();        // e.g. 'f3Gk9P...'
id(8);       // shorter id

Logger

Source: src/utils/logger.ts

The logger prints colored, timestamped logs and returns a structured LogEntry for each call.

  • log(message, data?, meta?) – info level.
  • log.info(...), log.success(...), log.warn(...), log.error(...) – level helpers.
  • log.withColor(color, message, data?, meta?) – custom color ('red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'gray').
import { log } from 'toolkit';

log('Server started', { port: 3000 });
log.success('User created', { id: 1 });
log.warn('Slow response', { ms: 1200 }, { context: 'GET /api/users' });
log.error('Failed to save', new Error('DB error'));
log.withColor('magenta', 'Custom log', { foo: 'bar' });

Data structures

Queue – toolkit/queue

Source: src/queue.ts

import { Queue } from 'toolkit/queue';

const q = new Queue<number>();
q.enqueue(1);
q.enqueue(2);
q.dequeue(); // 1
q.peek();    // 2

API:

  • enqueue(item)
  • dequeue()T | undefined
  • peek()T | undefined
  • length (getter)
  • isEmpty()
  • clear()

Stack – toolkit/stack

Source: src/stack.ts

import { Stack } from 'toolkit/stack';

const s = new Stack<number>();
s.push(1);
s.push(2);
s.pop();  // 2
s.peek(); // 1

API:

  • push(item)
  • pop()T | undefined
  • peek()T | undefined
  • length (getter)
  • isEmpty()
  • clear()

PriorityQueue – toolkit/priority-queue

Source: src/priorityQueue.ts

import { PriorityQueue } from 'toolkit/priority-queue';

const pq = new PriorityQueue<number>(); // min-heap by default
pq.enqueue(3);
pq.enqueue(1);
pq.enqueue(2);
pq.dequeue(); // 1

API:

  • constructor(compare?: (a, b) => number) – custom comparison function.
  • enqueue(item)
  • dequeue()T | undefined
  • peek()T | undefined
  • length (getter)
  • isEmpty()
  • clear()

Testing

The package includes a very small runtime smoke test:

npm test

This builds the TypeScript sources and runs test/basic.mjs against the compiled output in dist/.