Thingies: TypeScript Utility Library

2.6.0 · active · verified Sun Apr 19

Thingies is a versatile TypeScript utility library providing a collection of small, focused, and performant helpers for common programming tasks. It covers areas such as caching (LruCache, LruMap, LruTtlMap), promise management (Defer, of, promiseMap, until, tick, timeout), string manipulation (base64, hash, randomStr, normalizeEmail, dataUri), and concurrency control (Locks, codeMutex, concurrency, FanOut). The current stable version is 2.6.0, with frequent minor and patch releases introducing new features and performance improvements. Its key differentiator lies in its breadth of specific, often low-level, utilities, all designed with a TypeScript-first approach, offering strong typing and a comprehensive API for various Node.js and browser environments.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the usage of `LruCache` for in-memory caching, `of` for robust promise error handling, `codeMutex` for synchronizing concurrent operations, and `TimedQueue` for batching events based on count or time thresholds.

import { LruCache, of, codeMutex, TimedQueue } from 'thingies';

// 1. Using LruCache for efficient data storage
const userCache = new LruCache<string, { id: string; name: string }>({
  limit: 100, // Cache up to 100 users
  ttl: 60 * 1000, // Items expire after 60 seconds
});
userCache.set('user-1', { id: 'user-1', name: 'Alice' });
console.log('Cached user:', userCache.get('user-1'));

// 2. Safely handling Promise results with `of`
async function fetchData(shouldSucceed: boolean) {
  const [data, error] = await of(new Promise<string>((resolve, reject) => {
    setTimeout(() => {
      if (shouldSucceed) {
        resolve('Data fetched successfully');
      } else {
        reject(new Error('Failed to fetch data'));
      }
    }, 100);
  }));

  if (error) {
    console.error('Error fetching data:', error.message);
  } else {
    console.log('Data:', data);
  }
}

fetchData(true); // Should log data
fetchData(false); // Should log error

// 3. Using codeMutex for synchronized execution
const mutex = codeMutex();
let sharedResource = 0;

async function incrementResource(id: number) {
  await mutex(async () => {
    const current = sharedResource;
    await new Promise(resolve => setTimeout(resolve, Math.random() * 50)); // Simulate work
    sharedResource = current + 1;
    console.log(`Worker ${id}: sharedResource is now ${sharedResource}`);
  });
}

Promise.all([incrementResource(1), incrementResource(2), incrementResource(3)]);

// 4. Batching operations with TimedQueue
const eventQueue = new TimedQueue<string>({
  limit: 3, // Flush after 3 items
  timeout: 100, // Or flush after 100ms
  flush: async (items) => {
    console.log(`Flushing ${items.length} events: ${items.join(', ')}`);
    // In a real app, this would send to an external service or database
  },
});

eventQueue.push('event-A');
eventQueue.push('event-B');
eventQueue.push('event-C'); // This push should trigger a flush immediately

eventQueue.push('event-D');
eventQueue.push('event-E');
// Wait for timeout to flush remaining items
setTimeout(() => eventQueue.flush(), 200);

view raw JSON →