Code Snippet Library
Production-ready snippets for JavaScript, TypeScript, Python, Bash, SQL, CSS, Go, Rust, and PHP. Search, browse, and copy in one click.
88 snippets
Debounce Function
Delay function execution until after a wait period. Essential for search inputs.
Deep Flatten Array
Recursively flatten a nested array to any depth.
Group Array by Key
Group an array of objects by a property value.
Fetch with Retry
Retry a failed fetch up to N times with exponential back-off.
Safe localStorage Wrapper
Read and write to localStorage with JSON serialisation and error handling.
Minimal Event Emitter
Lightweight pub/sub pattern without any dependencies.
Copy Text to Clipboard
Write text to the clipboard with graceful fallback for older browsers.
Pick and Omit Object Keys
Select or exclude specific keys from an object without mutating it.
Deep Clone Object
Create a deep copy of a plain object or array using structuredClone.
Format Bytes to Human Size
Convert a raw byte count into a readable string like 1.4 MB.
Promise Pool (Concurrency Limit)
Run async tasks in parallel with a maximum concurrency limit.
Generic API Response Type
Typed wrapper for API responses with data, error, and loading states.
Exhaustive Switch Check
Compile-time guarantee that every union variant is handled.
DeepPartial Utility Type
Make every property in a nested object optional recursively.
Branded / Opaque Types
Prevent mixing structurally identical but semantically different types.
Result Type (Railway Pattern)
Represent success or failure without throwing exceptions.
Validated Environment Variables
Parse and validate process.env at startup with Zod so missing vars fail fast.
Type-Safe Fetch Wrapper
Generic fetch helper that parses JSON and narrows the response type.
Discriminated Union Type Guard
Runtime type guard for discriminated unions without casting.
Paginated Data Hook
React hook that manages paginated API calls with loading and error states.
Retry Decorator
Automatically retry a function on exception with configurable back-off.
Flatten Nested Dictionary
Flatten a deeply nested dict into dot-separated keys.
Batch Iterable into Chunks
Yield successive n-sized chunks from any iterable.
Timer Context Manager
Measure elapsed time of any code block with a context manager.
Dataclass to/from JSON
Serialize and deserialize a Python dataclass to a JSON string.
Load .env File into os.environ
Parse a .env file and inject variables without any third-party library.
Async HTTP Requests with asyncio
Fire multiple HTTP requests concurrently using asyncio and aiohttp.
Slugify String
Convert a title into a URL-safe slug.
Memoize with LRU Cache
Cache expensive function results with a fixed-size LRU cache.
Safe Script Header
Standard header that makes bash scripts exit on any error or undefined variable.
Check Required Commands
Fail early with a helpful message if a required binary is not installed.
Coloured Log Functions
Log helpers with timestamps and colour-coded severity levels.
Parse Named Arguments
Parse --flag=value style arguments in a bash script.
Retry a Command
Retry any command up to N times with a delay between attempts.
Auto-Cleanup Temp Directory
Create a temp directory that is removed automatically when the script exits.
Wait for Port to Open
Block script execution until a TCP port becomes available.
Export JSON as Environment Variables
Read a JSON file and export each top-level key as an env var.
Upsert (INSERT ... ON CONFLICT)
Insert a row or update it if a unique constraint is violated (PostgreSQL).
Keyset Pagination
Efficient pagination using a cursor instead of OFFSET for large tables.
Rank Rows within Groups
Use ROW_NUMBER to rank items per group, e.g. top product per category.
Recursive CTE (Tree Query)
Traverse a self-referential parent-child table with a recursive CTE.
Running Total with Window Function
Calculate a cumulative sum ordered by date without a subquery.
Pivot Rows to Columns
Turn row-based data into a pivot table using conditional aggregation.
Find and Remove Duplicate Rows
Identify duplicates and delete all but one, keeping the oldest row.
Query JSON Columns (PostgreSQL)
Extract fields from a JSONB column and filter on nested values.
Center Element Absolutely
Position an element in the exact center of its parent using transform.
Fluid Typography with clamp()
Scale font sizes fluidly between a min and max without media queries.
Styled Scrollbar
Custom scrollbar appearance for WebKit and Firefox.
Skeleton Loading Animation
Animated shimmer placeholder for content that is loading.
Sticky Header with Shadow on Scroll
Use a CSS scroll-driven animation to add a shadow when the page is scrolled.
Intrinsic Aspect Ratio Box
Lock an element to a specific aspect ratio using the aspect-ratio property.
CSS Custom Properties (Design Tokens)
Declare and use CSS variables for a scalable design token system.
Truncate Text with Ellipsis
Truncate single-line and multi-line text overflow with CSS.
Essential SEO Meta Tags
Core HTML meta tags for SEO, Open Graph, and Twitter Card.
Native HTML Dialog Modal
Accessible modal dialog using the native <dialog> element.
JSON-LD Structured Data
Add structured data (schema.org) to a page for rich search results.
Responsive Image with srcset
Serve appropriately sized images at different viewport widths.
HTTP JSON Handler
Write a JSON API handler with structured error responses in Go.
Worker Pool Pattern
Process jobs concurrently with a fixed pool of goroutines.
Retry with Exponential Back-off
Generic retry helper using a closure so it works for any operation.
Custom Error Enum with thiserror
Define a typed error enum with display messages using the thiserror crate.
Builder Pattern
Construct complex structs step-by-step with a fluent builder API.
Read File Line by Line
Iterate over lines of a file efficiently without loading it all into memory.
PDO Prepared Statement
Execute a parameterised SQL query safely using PDO.
Verify JWT Without a Library
Decode and verify the signature of a HS256 JWT using only built-in PHP functions.
Simple Rate Limiter with Redis
Limit requests per IP using Redis INCR and EXPIRE commands.
HTTP POST with cURL
Send a JSON POST request and decode the response using cURL.
Throttle Function
Ensure a function is called at most once per given interval.
Generate UUID v4
Generate a RFC-4122 compliant UUID without any library.
Async Sleep / Delay
Pause async code execution for a given number of milliseconds.
useLocalStorage React Hook
Sync React state to localStorage with TypeScript generics.
Validate Email Address
Check whether a string is a plausibly valid email address with a regex.
Parse and Format ISO 8601 Dates
Convert ISO 8601 strings to datetime objects and back.
Format Dates with Intl.DateTimeFormat
Format dates and times for any locale without a library.
Validate and Parse URLs
Check whether a string is a valid URL and extract its parts safely.
Multi-Key Sort
Sort an array by multiple properties with ascending or descending order.
Calculate Age in SQL
Calculate a person's current age in full years from a birth date column.
Delete Merged Git Branches
Remove all local branches that have already been merged into main.
Read and Decode a JSON File
Open a JSON file and decode it into a typed Go struct.
PHP Array Utility Helpers
Pluck, group-by, and unique-by helpers for arrays of associative arrays.
useDebouncedValue React Hook
Debounce a rapidly-changing value so only the settled value triggers effects.
Dark / Light Mode via data-theme
Implement a dark/light mode system using a data attribute on <html>.
Chunk List into Batches
Split a list into equal-sized chunks for batch processing.
Parse CLI Arguments with clap
Define a type-safe CLI interface using the clap derive API.
Lazy Load with IntersectionObserver
Load images or trigger animations when elements enter the viewport.
Full-Text Search (PostgreSQL)
Enable and query full-text search on a text column using tsvector.
Typed Event Bus
Strongly-typed publish/subscribe event bus using TypeScript generics.