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

Showing 91–120 of 770 public snippets

Rust
Trait with Default Methods
A trait can supply default implementations — implementors override only the bits they need. Like abstract base classes, but with structural typing and zero runtime cost.
3m ago 0
HTML
Sortable Table (semantic markup + JS hook)
Use `<button>` inside `<th>` and `aria-sort` on the column so screen readers announce sort state. The button is the keyboard-accessible trigger; JS only handles the actual sort.
3m ago 0
JavaScript
Base64 Encode & Decode (Unicode-safe)
Encodes and decodes strings to/from Base64. The native btoa/atob only handles Latin-1 characters, so these wrappers use TextEncoder/Uint8Array to handle the full Unicode range including emoji and CJK characters. Useful for encoding binary data, tokens, and payloads for URLs or localStorage.
3m ago 0
Bash
PID File Management
Write a daemon's PID to a file at start, check on subsequent runs, clean up on exit. Avoids two copies of the same daemon when the script is invoked twice.
3m ago 0
Bash
Show Current Branch in Prompt
Append the git branch to your bash prompt. Survives non-git dirs gracefully (just shows nothing). Drop into ~/.bashrc.
3m ago 0
HTML
Visually Hidden Utility (.sr-only)
Hides content from sighted users but keeps it discoverable by screen readers. Use for icon-only buttons, table-row context, and form-status announcements that don't need visible text.
3m ago 0
PHP
Levenshtein Similarity Percentage
Wrap PHP's built-in levenshtein() to return a similarity score from 0.0 (totally different) to 1.0 (identical). Handy for "did you mean…?" suggestions.
3m ago 0
Go
Multiple Return Values + Named Returns
Go functions can return multiple values — most idiomatically a `(result, error)` pair. Named returns let you document the meaning of each value AND enable naked returns in short functions.
3m ago 0
JavaScript
JSON Fetch Wrapper
A thin wrapper around fetch that automatically serialises the request body to JSON, sets the Content-Type header, parses the response as JSON, and throws a descriptive error on non-OK responses. Covers the boilerplate needed for 95% of REST API calls in a single reusable function.
3m ago 0
JavaScript
Animate Counter (Number Roll-Up)
Smoothly animates a number from a start value to an end value over a given duration using requestAnimationFrame. Supports a custom easing function (defaults to ease-out quad). Ideal for dashboard stat widgets, donation counters, and any UI where a bare static number would be less impactful.
3m ago 0
HTML
Favicon Set (SVG + PNG fallbacks)
Modern favicon setup: one SVG that scales, an ICO fallback for old browsers, and an apple-touch-icon for iOS home screens. Skip the 12-file <link> dump from favicon generators of yore.
3m ago 0
Bash
Most-Modified Files in Repo
Find the hottest files in a git history — useful for spotting hotspots that need refactoring or extra test coverage.
3m ago 0
Kotlin
Default Arguments + Named Parameters
Default values eliminate most overload sets. Named args make call sites self-documenting and let you skip middle parameters without thinking about positions.
3m ago 0
JavaScript
Capitalize Words (Title Case)
Converts a string to title case by capitalising the first letter of each word. Handles multiple spaces and mixed-case input. Optionally skips common English stopwords (a, an, the, of, in, …) so article/preposition words are not capitalised in the middle of a title — matching standard editorial style guides.
4m ago 0
Rust
Custom Iterator Implementation
Implementing `Iterator` is just supplying a `next() -> Option<Item>`. You automatically gain `map`, `filter`, `collect`, and every other adapter for free.
4m ago 0
Java
Files.readString / readAllLines
`java.nio.file.Files` shipped these convenience helpers in Java 8/11. Way cleaner than the legacy `FileReader` + `BufferedReader` ceremony for small/medium files.
4m ago 0
PHP
URL Slug Generator (UTF-8 safe)
Convert any string into a clean URL-safe slug. Transliterates accented characters to ASCII, lowercases, replaces non-alphanumerics with dashes, and collapses runs of dashes. Works on UTF-8 input out of the box.
4m ago 0
SQL
ARRAY_AGG and JSON_AGG (PostgreSQL)
Roll up grouped rows into a PostgreSQL array or JSON array — often a faster replacement for the application doing the same "group children under parent" join.
4m ago 0
JavaScript
Simple State Machine
A lightweight finite state machine that defines valid states and allowed transitions between them. Attempting an invalid transition throws an error. Supports entry/exit hooks per state for side effects. Useful for modelling UI flows (idle → loading → success/error), auth states, and multi-step forms.
5m ago 0
JavaScript
Validate Email Address
Validates an email address using a battle-tested regex that covers the vast majority of real-world addresses without being overly strict. For server-side code, pair this with a confirmation email step — client-side regex alone is not a security measure. Returns a boolean for easy conditional use.
5m ago 0
JavaScript
Truncate String
Truncates a string to a maximum character length and appends an ellipsis (or custom suffix). The smart version breaks at the last word boundary to avoid cutting in the middle of a word, making truncated text look natural in card previews, notifications, and list views.
5m ago 0
JavaScript
Parse URL Query String
Parses a URL query string into a plain key-value object. Uses the built-in URLSearchParams API — no regex required. Handles duplicate keys (returns the first value), percent-encoded characters, and works with both full URLs and raw query strings. Pairs nicely with buildQueryString.
5m ago 0
JavaScript
Scroll to Element Smoothly
Scrolls the page to a target element with an optional pixel offset (useful when a fixed header is present). Uses the native scrollIntoView with smooth behaviour when supported, and falls back to a manual scrollTo with a configurable offset. Pass a CSS selector string or an Element reference.
5m ago 0
JavaScript
Calculate Reading Time
Estimates the reading time of a block of text based on an average adult reading speed (default 200 words per minute). Strips HTML tags before counting to handle rich-text content. Returns the result in minutes, rounded up, so a short article always shows at least "1 min read".
5m ago 0
JavaScript
Long Polling Helper
Implements a long-polling loop that repeatedly calls a fetch endpoint and invokes a callback with the result. Backs off exponentially on errors and stops cleanly when cancelled via the returned stop function. A simple alternative to WebSockets for low-frequency server-push events without SSE support.
5m ago 0
JavaScript
Delegate Event Listener
Attaches a single event listener to a parent element and handles events from matching descendant elements via event delegation. More efficient than attaching listeners to many individual elements, and works for elements added dynamically to the DOM after the listener is registered.
5m ago 0
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
Promise All with Concurrency Limit
Runs an array of async tasks with a maximum concurrency cap, preventing you from firing hundreds of requests simultaneously. Processes items in batches, moving to the next as slots free up. Essential when hitting rate-limited APIs or processing large datasets without overwhelming the server.
5m ago 0
JavaScript
Flatten Nested Array
Recursively flattens an array of arbitrary nesting depth into a single flat array. Accepts an optional depth limit — pass Infinity to flatten completely. Uses the native Array.flat when the browser supports it, otherwise falls back to a recursive reduce.
5m ago 0
JavaScript
Pick & Omit Object Keys
pick returns a new object containing only the specified keys. omit returns a new object with the specified keys removed. Both are pure (non-mutating) and handle missing keys gracefully. Essential for cleaning API payloads, projecting data shapes, and avoiding over-sending sensitive fields.
5m ago 0