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';npm install toolkitSource: src/utils/string.ts
-
trim(text)– safely trims, treatingnull/undefinedas''. -
toLower(text)/toUpper(text)– lower/upper‑case after trimming. -
isEmpty(text)–trueif empty or only whitespace. -
capitalize(text)–"hello WORLD"→"Hello world". -
slug(text)– URL‑friendly slug,"Hello World!"→"hello-world". -
includes(text, search)– safe wrapper aroundString.prototype.includes. -
startsWith(text, prefix)– safe wrapper aroundstartsWith. -
endsWith(text, suffix)– safe wrapper aroundendsWith. -
words(text)– splits on whitespace, collapsing multiples.
trim(' hi '); // 'hi'
capitalize('hELLO'); // 'Hello'
slug('Hello World!'); // 'hello-world'Source: src/utils/number.ts
-
clamp(value, min, max)– clamps into[min, max](NaN →min). -
toNumber(value, fallback?)– safeNumber()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,0for 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.5Source: src/utils/array.ts
-
uniq(items)– unique items, first occurrence wins. -
chunk(items, size)– splits into chunks. -
compact(items)– removesnull/undefined/false(keeps0and''). -
flat(items)– flattens one level. -
first(items)/last(items)– first/last item orundefined. -
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 inathat are not inb. -
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');Source: src/utils/object.ts
-
merge(a, b)– shallow merge,boverridesa. -
get(obj, path, fallback?)– safe deep property access ('a.b.c'). -
isEmptyObject(value)– own enumerable keys length is0. -
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']);Source: src/utils/async.ts
-
sleep(ms)– Promise that resolves afterms. -
handlePromise(fn)– wraps any async function and returns{ success, data, error }, auto-unwrapping.datawhen present (e.g. axios). -
timeout(promise, ms)– reject if promise doesn’t settle inms. -
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);Source: src/http.ts
-
buildQuery(params)– builds a query string from a flat object. -
withAbort()– returns{ signal, abort }usingAbortController. -
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' });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 inYYYY-MM-DDformat (UTC). -
getYesterdayDate()– yesterday's date inYYYY-MM-DDformat (UTC). -
startOfDay(date)– midnight for that day. -
isBefore(a, b)– true ifa < 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"Source: src/utils/json.ts
-
parseJson(text)– safeJSON.parse, returnsundefinedon error. -
stringifyJson(value, replacer?, space?)– safeJSON.stringify, returnsundefinedon error.
parseJson('{"a":1}'); // { a:1 }
parseJson('{bad}'); // undefined
stringifyJson({ a: 1 }); // '{"a":1}'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\nSource: src/utils/compare.ts
Safely compares any two values, handling numbers, strings, objects, and mixed types.
-
compare(a, b, key?)– returns-1ifa < b,0ifa === b,1ifa > 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 ifa < b. -
isGreaterThan(a, b, key?)/gt(a, b, key?)– checks ifa > b. -
isLessThanOrEqual(a, b, key?)/lte(a, b, key?)– checks ifa <= b. -
isGreaterThanOrEqual(a, b, key?)/gte(a, b, key?)– checks ifa >= 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); // trueSource: src/utils/id.ts
-
id(length = 16)– random alphanumeric ID, usingcrypto.getRandomValueswhen available, otherwiseMath.random.
id(); // e.g. 'f3Gk9P...'
id(8); // shorter idSource: 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' });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(); // 2API:
enqueue(item)-
dequeue()→T | undefined -
peek()→T | undefined -
length(getter) isEmpty()clear()
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(); // 1API:
push(item)-
pop()→T | undefined -
peek()→T | undefined -
length(getter) isEmpty()clear()
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(); // 1API:
-
constructor(compare?: (a, b) => number)– custom comparison function. enqueue(item)-
dequeue()→T | undefined -
peek()→T | undefined -
length(getter) isEmpty()clear()
The package includes a very small runtime smoke test:
npm testThis builds the TypeScript sources and runs test/basic.mjs against the compiled output in dist/.