SaveSnippets
Community
Pricing
Sign In
Get Started
@admin
ADMIN
Member since Apr 2026
770
Public snippets
5
Net score
5
Total upvotes
Showing
391–420
of
770
public snippets
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.
5h 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.
5h 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.
5h 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.
5h 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.
5h 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.
5h 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.
5h 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.
5h 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.
5h 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.
5h 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.
5h ago
0
TypeScript
Branded Types (nominal typing)
TypeScript is structurally typed, so `string` and `string` are interchangeable even when they semantically aren't (UserId vs PostId). The "brand" trick adds a phantom property that exists only at compile time, giving you nominal-ish typing.
5h ago
0
TypeScript
useClickOutside — Detect Outside Clicks
Fire a callback when the user clicks anywhere outside a referenced element. Perfect for closing dropdowns, popovers, and modal-less menus.
5h 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.
5h ago
0
Python
Stdlib .env Loader (no dependency)
Parse a `.env` file into a dict and optionally export to os.environ. Skips comments and blank lines, strips surrounding quotes — no python-dotenv dependency needed.
5h 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.
5h 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.
5h 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.
5h 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).
5h 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.
5h 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.
5h ago
0
TypeScript
Mapped Types (Partial/Required/etc)
Mapped types iterate over keys to produce new types. The standard library's `Partial`, `Required`, `Readonly`, `Pick`, `Omit`, `Record` are all one-liners — and you can build your own.
5h ago
0
Bash
Generate a Random Password
Three approaches: pwgen (purpose-built), openssl (universally available), /dev/urandom + tr (zero deps). Pick by what's installed.
5h ago
0
Bash
Source Multiple Files from Directory
A common ~/.bashrc / ~/.zshrc pattern: split your config into ~/.bashrc.d/*.sh and source them all. Easier than one giant file.
5h ago
0
Go
Graceful HTTP Shutdown
On SIGINT/SIGTERM, stop accepting new connections but let in-flight requests finish. The `http.Server.Shutdown` method does exactly that — with a deadline.
5h ago
0
PHP
Validate UUID (any version)
Match the canonical 8-4-4-4-12 hex format, optionally pinning to a specific UUID version (1-5). Case-insensitive.
5h ago
0
PHP
Normalize Phone Number to E.164
A minimal E.164 normalizer for US/CA numbers — strips formatting, prepends "+1" if missing, and validates the digit count. For full international support, reach for giggsey/libphonenumber-for-php.
5h ago
0
TypeScript
usePrevious — Track Last Render's Value
Returns the value the prop/state had on the previous render. Useful for detecting transitions (e.g. "the count just went from 0 to 1") inside effects.
5h ago
0
Bash
ANSI Color Output Helpers
Wrap printf with ANSI escape codes for color and bold. Auto-disable if stdout isn't a TTY (so piping to a file doesn't pollute it with escape sequences).
5h ago
0
Rust
Newtype Pattern (zero-cost wrappers)
Wrap a primitive in a tuple struct to give it a distinct type identity at the type level — without runtime cost. Replaces "is this number a UserId or a PostId?" bugs.
5h ago
0
1
…
12
13
14
15
16
…
26