55 snippets · production-ready JavaScript & TypeScript
A production-ready DataFetcher<T> component implementing the render props pattern in TypeScript React, with full type safety for loading, error, and success states.
A generic React hook that stores and returns the value from the previous render cycle, useful for comparing state changes and triggering animations.
A generic React hook that debounces any value by a specified delay in milliseconds, perfect for optimizing search inputs, API calls, and other performance-sensitive operations.
A complete implementation of the compound component pattern in React TypeScript, demonstrating how to build a flexible Tabs component (Tabs, Tabs.List, Tabs.Tab, Tabs.Panel) using Context API to share state without prop drilling.
A type-safe React hook that listens to CSS media queries and returns a boolean indicating whether the query matches. Handles SSR gracefully and cleans up listeners automatically.
A fully typed React hook for persisting state to localStorage with automatic JSON serialization, SSR compatibility, and real-time synchronization across browser tabs.
A custom React hook that fetches data with automatic request cancellation on unmount and race condition prevention using AbortController.
A production-ready React hook that wraps the Intersection Observer API, returning a ref and isIntersecting boolean with configurable threshold and rootMargin options.
A TypeScript function that recursively merges two objects with full type safety. Arrays are concatenated, primitives are overwritten by the source, and nested objects are merged recursively.
A reusable TypeScript async generator function that handles API pagination automatically, fetching pages sequentially and yielding items until all data is retrieved.
A production-ready TypeScript WorkerPool class that maintains a pool of Web Workers, automatically distributes tasks to idle workers, queues tasks when all workers are busy, and provides type-safe Promise-based results.
A production-ready TypeScript Builder pattern implementation using generics to track set fields and enforce required properties at compile time, ensuring objects are only buildable when all required fields are provided.
Production-ready TypeScript utilities for reading JSON files with Zod schema validation and writing JSON files atomically using temporary files and rename operations.
An async generator function that recursively traverses a directory tree, yielding file paths that match include/exclude glob patterns with configurable maximum depth.
A TypeScript utility function that wraps any promise and automatically rejects with a custom TimeoutError if the promise doesn't resolve within a specified time limit.
A production-ready deep clone utility that leverages the native structuredClone API when available, with a comprehensive manual fallback that correctly handles special object types and circular references.
A production-ready async retry utility that implements exponential backoff with jitter. Supports configurable max attempts, base delay, max delay cap, and an optional error filter predicate to selectively retry specific errors.
A complete TypeScript Result<T, E> implementation providing type-safe error handling with Ok and Err variants, utility functions for transformation and extraction, and practical async usage examples.
A TypeScript EventEmitter class that provides complete type safety for event names and payloads using generics and mapped types, ensuring compile-time validation of all event operations.
Implements TypeScript branded types (nominal typing) to create distinct types from primitives, preventing accidental type confusion between semantically different values like UserId and PostId.
A production-ready memoization utility that intelligently caches function results using WeakMap for object arguments (preventing memory leaks) and Map for primitive values, with support for custom cache key serialization.
A framework-agnostic TypeScript utility that calculates which items should be rendered in a virtual scrolling list based on scroll position, container dimensions, and item metrics.
A custom React hook that enables optimistic UI updates by immediately reflecting user actions while async operations complete in the background, with automatic rollback on failure.
A TypeScript implementation of createSelectableContext that provides a useContextSelector hook, allowing components to subscribe to specific slices of context state and re-render only when those slices change.
A TypeScript hook that returns a stable function reference (identity-stable across renders) while ensuring it always invokes the most recent callback. Essential for optimizing React performance with memoized components.
A complete implementation of the Observable pattern in TypeScript, featuring core operators (map, filter, take) and demonstrating reactive event stream handling without external dependencies.
A production-ready TypeScript Semaphore implementation that controls concurrent async operations, featuring acquire/release semantics and automatic cleanup for rate-limiting scenarios.
Demonstrates powerful TypeScript template literal types that enforce string patterns at compile time, including event naming conventions, CSS properties, route parameter extraction, and tuple joining.
A complete TypeScript implementation for gracefully shutting down Node.js HTTP servers, handling OS signals, tracking in-flight requests, and ensuring all connections complete before exit.
A production-ready TypeScript implementation of a Node.js stream pipeline that processes large CSV files efficiently using stream/promises pipeline(), custom Transform streams for parsing and filtering, with proper error handling and backpressure support.
A complete HTTP client implementation using Node.js built-in http and https modules, featuring typed responses, automatic JSON handling, redirect following, and configurable timeouts.
A TypeScript utility that deduplicates concurrent requests by sharing a single in-flight promise among all callers requesting the same resource, preventing redundant network calls and improving application performance.
A fully-featured Least Recently Used (LRU) cache implementation in TypeScript with O(1) get/set/delete operations, optional time-to-live per entry, and customizable eviction callbacks.
A TypeScript pattern for creating type-safe API clients where request parameters and response types are automatically inferred from a route definition object, eliminating the need for code generation tools.
A factory function that wraps objects in a Proxy, validating all property assignments against a Zod schema at runtime while maintaining transparent read access.
A production-ready TypeScript implementation of an observable object pattern using Proxy, featuring deep reactivity for nested objects, batch update capabilities to minimize notifications, and fully typed subscription callbacks.
A collection of TypeScript sliding window algorithm implementations for common array and string processing tasks, optimized for O(n) time complexity.
A TypeScript utility that wraps Promise.allSettled and provides strongly-typed discriminated unions for success and failure results, with type guard helpers for easy filtering.
A comprehensive collection of generic binary search variants in TypeScript, including classic binary search, lower bound, upper bound, and search range functions with support for custom comparators.
A TypeScript implementation of an async queue that processes tasks with a configurable concurrency limit, ensuring controlled parallel execution of asynchronous operations.
A production-ready debounce utility specifically designed for async functions. It cancels previous pending calls and always resolves with the result of the most recent invocation.
A comprehensive collection of advanced TypeScript mapped types that transform object types in powerful ways, enabling precise type manipulation for real-world applications.
A generic TypeScript function that splits an array into smaller arrays (chunks) of a specified size, with proper handling for all edge cases.
A generic TypeScript function that groups array elements by a computed key, returning a Record<string, T[]> where each key maps to an array of matching elements.
A generic TypeScript function that removes duplicate elements from an array based on a custom key selector function, preserving the first occurrence of each unique key.
A fully type-safe TypeScript function that recursively flattens deeply nested arrays of arbitrary depth, preserving the element type through advanced conditional type inference.
A type-safe TypeScript function that zips multiple arrays together into tuples, similar to Python's zip(). Handles arrays of different lengths by stopping at the shortest one.
Production-ready pick and omit utility functions that leverage TypeScript's type system to create perfectly typed object subsets with full inference support.
A recursive TypeScript function that transforms nested objects into flat objects with dot-notation keys, supporting custom separators and proper type safety.
Learn to create powerful type utilities using TypeScript's conditional types and infer keyword, including UnwrapPromise, ReturnType, Parameters, and array element extraction.
A production-ready TypeScript utility that wraps fetch with an in-memory cache using Map, supports TTL-based expiration, and deduplicates concurrent requests to the same URL.
A production-ready TypeScript wrapper around fetch that validates API responses against Zod schemas at runtime, providing full type safety and structured error handling.
A production-ready TypeScript RateLimiter class that enforces rate limits on API calls by queuing excess requests and automatically processing them when the rate limit window resets.
A production-ready TypeScript utility that wraps child_process.spawn to execute shell commands, stream output to the console in real-time, and return the exit code via a Promise.
A TypeScript utility that validates environment variables against a Zod schema at application startup, providing type-safe access to env vars and clear error messages when validation fails.