A collection of TypeScript utility functions for common operations on arrays, strings, objects, and more.
npm install @mtinner/utility-functionsequals- Check if two arrays are equalisSuperSet- Check if first array contains all elements of second arrayintersection- Get common elements between two arraysuniqueById- Remove duplicates based onidpropertyunique- Remove duplicate valuesmoveElement- Move array element up or downmapByKey- Convert array to object mapped by specified keypartition- Split array into two based on predicate function
slice- Slice string to maximum charactersshorten- Truncate string and add ellipsistoSeoString- Convert string to SEO-friendly format
typedKeys- Get object keys with proper typingintersectKeysToObject- Create object with only overlapping keys
times- Execute function multiple timesmemoize- Cache function results with optional TTL and cache controlsTaskScheduler- Run async tasks with a concurrency limit and abort support
import { unique, intersection } from '@mtinner/utility-functions/array';
import { toSeoString } from '@mtinner/utility-functions/to-seo-string';
import { typedKeys } from '@mtinner/utility-functions/object';
// Remove duplicates
const numbers = unique([1, 2, 2, 3]); // [1, 2, 3]
// Find common elements
const common = intersection([1, 2, 3], [2, 3, 4]); // [2, 3]
// Create SEO string
const seo = toSeoString('Hello World!'); // 'hello-world'
// Get typed object keys
const obj = { name: 'John', age: 30 };
const keys = typedKeys(obj); // ('name' | 'age')[]
// Memoize an expensive function (optional TTL in ms)
const expensiveAdd = (a: number, b: number) => {
// pretend this is slow
return a + b;
};
const { memoizedFunction: add, clearCache, size } = memoize(expensiveAdd, { ttl: 5000 });
add(2, 3); // 5 (computed)
add(2, 3); // 5 (cached within TTL)
size(); // 1 (number of non-expired cache entries)
clearCache();
size(); // 0
// Run tasks with limited concurrency and abort support
const scheduler = new TaskScheduler(2); // max 2 concurrent tasks
const controller = new AbortController();
const task = async (signal: AbortSignal) => {
await new Promise((r) => setTimeout(r, 200));
if (signal.aborted) throw new Error('aborted');
return 'done';
};
scheduler.add(task, controller.signal).then(console.log).catch(console.error);
// controller.abort(); // optionally abortimport { unique, intersection } from '@mtinner/utility-functions/array';import { slice, shorten } from '@mtinner/utility-functions/string';
import { toSeoString } from '@mtinner/utility-functions/to-seo-string';import { typedKeys, intersectKeysToObject } from '@mtinner/utility-functions/object';import { times } from '@mtinner/utility-functions/times';import { memoize } from '@mtinner/utility-functions/memoize';import { TaskScheduler } from '@mtinner/utility-functions/task-scheduler';This library is written in TypeScript and includes full type definitions for better developer experience and type safety.
MIT