admin
@admin ADMIN
Member since Apr 2026
770
Public snippets
5
Net score
5
Total upvotes

Showing 121–150 of 770 public snippets

JavaScript
Queue (Async Task Queue)
A serialised async task queue that executes queued async functions one at a time, in order. Useful for sequencing operations that must not run concurrently (file writes, ordered API mutations, step-by-step wizards). add() returns a Promise that resolves/rejects when that specific task completes.
5m ago 0
JavaScript
Slugify String
Converts any string into a URL-safe slug: lowercases it, replaces accented characters with ASCII equivalents, strips all non-alphanumeric characters (except hyphens), and collapses multiple hyphens into one. Ideal for generating URL slugs from blog titles, product names, or user input.
5m ago 0
JavaScript
Async Sleep / Delay
Returns a Promise that resolves after a given number of milliseconds. Use with await to pause async functions without blocking the main thread. More readable than nested setTimeout callbacks and composable with other async utilities.
5m ago 0
JavaScript
Fetch with Retry
Wraps the native fetch API with automatic retry logic using exponential backoff. Retries on network errors or non-OK HTTP responses up to a configurable number of attempts. Exponential backoff with optional jitter prevents thundering herd problems when many clients retry simultaneously.
5m ago 0
JavaScript
Unique Array Values
Returns a new array with duplicate values removed. The fast version uses a Set for primitives. The deep version supports deduplicating objects by a specific key, making it suitable for deduplicating API results or merged data sets.
5m ago 0
JavaScript
Deep Merge Objects
Recursively merges two or more objects, combining nested properties rather than overwriting them. Unlike Object.assign or spread, this preserves deep keys from all sources. Useful for merging configuration objects, default settings with user overrides, and API response patching.
5m ago 0
JavaScript
Intersection Observer (Lazy Load / Reveal)
Uses the IntersectionObserver API to trigger a callback when elements enter the viewport. The reveal pattern adds a visible class to animate elements as they scroll into view. The lazyLoad pattern loads images on demand by swapping data-src to src. Much more performant than scroll event listeners.
5m ago 0
JavaScript
Web Crypto — AES-GCM Encrypt & Decrypt
Encrypts and decrypts text using AES-GCM (256-bit) via the browser's native Web Crypto API — no external library needed. A random 96-bit IV is generated per encryption and prepended to the output so decryption can recover it. Suitable for encrypting sensitive data client-side before storage.
5m ago 0
Python
flatten — Recursively Flatten Nested Lists
Yield every leaf from arbitrarily-nested lists/tuples. Strings are intentionally treated as atomic (we don't want to "flatten" "hi" into ["h", "i"]).
5m ago 0
JavaScript
Throttle
Ensures a function is called at most once per specified time interval, no matter how many times the trigger fires. Ideal for scroll listeners, mousemove handlers, and window resize events where you need regular updates but not every single frame.
6m ago 0
JavaScript
Debounce
Delays invoking a function until after a specified wait time has elapsed since the last time it was called. Essential for search inputs, resize handlers, and any event that fires rapidly — prevents excessive function calls and improves performance.
6m ago 0
JavaScript
Copy Text to Clipboard
Copies a string to the system clipboard. Uses the modern navigator.clipboard.writeText API (requires HTTPS or localhost) and falls back to the deprecated document.execCommand approach for older browsers or non-secure contexts. Returns a Promise so you can show success/error feedback.
6m ago 0
JavaScript
DOM Ready Helper
Runs a callback when the DOM is fully parsed and ready, without waiting for images or stylesheets. Works whether called before or after DOMContentLoaded has already fired — unlike a bare addEventListener which misses the event if the DOM is already ready when the script runs.
6m ago 0
JavaScript
String Template Tag — SQL / HTML Sanitiser
A tagged template literal that automatically escapes interpolated values, preventing SQL injection (server-side) or XSS (client-side) from untrusted input. The html tag HTML-encodes values; the sql tag parameterises values and returns a { text, values } tuple ready for a parameterised query driver.
6m ago 0
JavaScript
Shuffle Array (Fisher-Yates)
Randomly shuffles an array in-place using the Fisher-Yates algorithm, which produces a uniformly random permutation. Widely considered the correct way to shuffle — avoids the bias inherent in sort(() => Math.random() - 0.5). Returns the same array reference after shuffling.
6m ago 0
JavaScript
Format File Size
Converts a raw byte count into a human-readable string with the appropriate unit (B, KB, MB, GB, TB). Uses 1024-based (binary) units by default or optionally 1000-based (SI) units. Useful for upload progress indicators, file browsers, and storage dashboards.
6m ago 0
JavaScript
UUID v4 Generator
Generates a RFC 4122 compliant version-4 UUID. Uses crypto.randomUUID() in modern environments (Node 14.17+, all modern browsers) and falls back to a Math.random()-based implementation for older runtimes. The fallback is suitable for non-security-critical IDs such as UI element keys and local correlation IDs.
6m ago 0
JavaScript
Download File from Client
Programmatically triggers a file download from a Blob, File object, or plain text/JSON string without a server round-trip. Creates a temporary anchor element with a download attribute and revokes the object URL after use to prevent memory leaks. Supports custom filenames and MIME types.
6m ago 0
JavaScript
Detect Mobile / Device Type
Detects whether the user is on a mobile, tablet, or desktop device. The navigator.userAgentData API (Chromium) is preferred for its structured data; falls back to a User-Agent regex for Safari and Firefox. Useful for conditional rendering, touch event handling, and analytics segmentation.
6m ago 0
JavaScript
Observable / Reactive State
A minimal reactive state container. Wrap any object with observable() and it returns a Proxy that notifies subscribers whenever a property is set. subscribe() registers a listener that receives the changed key and new value. A lightweight alternative to MobX or Vue's reactive() for small-scale reactivity needs.
6m ago 0
Bash
Detect Whether Running as Root
Several scripts must run as root (or refuse to). EUID is more reliable than `whoami == root` because sudo without -E may change one but not the other.
7m ago 0
SQL
Pagination with LIMIT / OFFSET
`LIMIT N OFFSET M` is universal — but degrades on deep pages (the DB still has to scan past M rows). Keyset (cursor) pagination is much faster for huge tables.
7m ago 0
Rust
Rc and Arc — Shared Ownership
`Rc<T>` lets multiple owners share read-only access in single-threaded code; `Arc<T>` is the thread-safe version. Pair with `RefCell` / `Mutex` when you need shared MUTABLE access.
7m ago 0
Bash
Spinner During Long Task
Show a rotating spinner next to a status message while a background command runs. Cosmetic but vastly improves the user experience of long scripts.
7m ago 0
Go
Methods and Receivers
Methods are functions with a receiver argument. Use pointer receivers when you mutate, when the struct is large, OR for consistency (mixing pointer + value receivers on the same type is a common bug source).
7m ago 0
HTML
Native <dialog> Modal
The HTML `<dialog>` element gives you a real modal — focus trap, Escape-to-close, backdrop overlay — without any JS library. Method `.showModal()` opens; `.close()` closes.
7m ago 0
TypeScript
Deep Clone with structuredClone
Forget JSON.parse(JSON.stringify(...)) — modern runtimes (Node 17+, all current browsers) ship structuredClone, which handles Dates, Maps, Sets, typed arrays, and cycles correctly.
7m ago 0
Bash
Memory / CPU / Load Quick Check
One-liners for the three most-requested system metrics. Use in monitoring scripts or as ad-hoc sanity checks.
7m ago 0
Rust
Custom Display + Debug Implementation
`Debug` (for `{:?}`) is usually derived. `Display` (for `{}`) is hand-written and goes through the same `std::fmt::Formatter` API.
7m ago 0
Go
Generic Function with Type Parameters
Go 1.18+ generics. `[T any]` is unconstrained; `[T comparable]` allows == and !=; custom constraints work too. The compiler infers T from arguments.
7m ago 0