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

Showing 1–30 of 770 public snippets

JavaScript
Middleware Pipeline
A simple Koa/Express-style middleware runner for client-side use. Middleware functions receive a context object and a next() function — call next() to pass control to the next middleware or skip it to short-circuit the chain. Useful for building plugin systems, request pipelines, and composable validation logic.
9m ago 1
JavaScript
Flatten Object (Dot Notation)
Flattens a deeply nested object into a single-level object with dot-notation keys. Useful for comparing configs, building form field names from nested data, logging structured objects to analytics, or preparing data for flat key-value stores like Redis or environment variables.
9m ago 1
JavaScript
Serialize Form to Object
Converts all named form fields into a plain JavaScript object using the FormData API. Handles text inputs, selects, textareas, and checkboxes. Multiple values for the same name (e.g. multi-select, checkboxes) are collected into an array. Ready to JSON.stringify and POST to an API.
9m ago 1
JavaScript
i18n Minimal Translator
A tiny internationalisation helper that loads a locale dictionary and resolves translation strings by dot-notation key. Supports variable interpolation via {{placeholder}} syntax. Falls back to the key itself when a translation is missing, keeping the UI readable during development. Swap the locale at runtime without a page reload.
9m ago 1
JavaScript
Cookie Helpers (Get / Set / Delete)
Minimal cookie utilities: getCookie retrieves a value by name, setCookie writes a cookie with optional expiry days and path, deleteCookie removes it by setting an expired date. No library needed for simple first-party cookie management. For complex scenarios (SameSite, Secure, partitioned) extend the options object.
9m ago 1
PHP
Build & Sign a JWT (HS256)
Generate a JWT manually using only base64-url and hash_hmac — no library required. Demonstrates header/payload/signature concatenation and the exp claim.
1m ago 0
Kotlin
StateFlow — Observable State
`StateFlow<T>` is a hot Flow holding a single current value. Perfect for UI state in Compose/Android — always has a value, conflates intermediate values, multi-subscriber.
1m ago 0
Kotlin
kotlin.time — Duration and measureTime
`kotlin.time.Duration` is a typesafe time amount with friendly literal syntax (`5.seconds`, `2.minutes`). `measureTime { }` benchmarks a block.
2m ago 0
Kotlin
ViewModel + StateFlow + Compose
Standard Android pattern: ViewModel holds state in a `StateFlow`, Compose collects it as state. Survives config changes; isolates business logic from UI.
3m ago 0
Kotlin
Sealed Interfaces (Kotlin 1.5+)
Like sealed classes, but for interfaces — and a class can implement multiple sealed interfaces. Cleaner state modeling when you want "this is both a Loadable and a Cacheable".
4m ago 0
SQL
ROW_NUMBER OVER PARTITION
Number rows within a partition — the most common "give me the Nth thing per group" pattern. Pair with a WHERE rn = 1 in an outer query to keep just the top row per group.
4m ago 0
Go
Type Switches
When you have an `interface{}` (or any) and need to dispatch on its underlying type, use `switch v := x.(type)`. Cleaner than a chain of type-assertions.
5m ago 0
Go
Custom Generic Constraints
Type constraints are interfaces with type sets. Use them to express "any numeric" or "any ordered" without resorting to `any`.
5m ago 0
TypeScript
partition — Split by Predicate
Split an array into [pass, fail] in a single pass. Type guard overload lets the truthy bucket get a narrowed type when you pass a `x is T` predicate.
6m ago 0
Go
Interface Segregation — Small Interfaces
"The bigger the interface, the weaker the abstraction." Go encourages small, focused interfaces (often just one method) — io.Reader, io.Writer, fmt.Stringer. Define them at the consumer side.
6m ago 0
PHP
Partition Array Into Two Buckets
Split an array into [matches, non-matches] using a predicate callback. Single pass, preserves order, returns two lists.
6m ago 0
SQL
Running Totals (SUM OVER)
Window aggregates with an implicit "rows up to here" frame give you running totals, cumulative counts, and ratchet-up metrics. No self-join needed.
6m ago 0
TypeScript
takeWhile / dropWhile
Consume or skip leading elements as long as a predicate holds. Useful for parsing prefixed sequences (e.g. all leading whitespace tokens, all unread notifications, etc.).
8m ago 0
JavaScript
Chunk Array
Splits an array into smaller arrays (chunks) of a specified size. The last chunk may be smaller if the array length is not evenly divisible. Useful for batch processing, pagination, rendering large lists in chunks, and rate-limited API calls.
9m ago 0
JavaScript
Detect Dark Mode Preference
Reads the user's OS-level dark mode preference using the prefers-color-scheme media query and watches for live changes. Useful for initialising theme state before any user interaction and reacting automatically when the user switches their system theme without reloading the page.
9m ago 0
JavaScript
IndexedDB Wrapper
A Promise-based wrapper for the IndexedDB API — simplifies the verbose request/onsuccess/onerror pattern into clean async/await calls. Supports get, set, delete, and getAll operations on a named object store. Ideal for storing large client-side datasets, offline data, and blobs that exceed localStorage limits.
9m ago 0
HTML
ARIA Live Region for Dynamic Announcements
Use `aria-live` on a container so screen readers announce its content changes (toast notifications, form errors, loading states). `polite` waits for a pause; `assertive` interrupts.
10m ago 0
HTML
HTML5 Document Boilerplate
Sensible HTML5 starting template: UTF-8 charset, responsive viewport, language attribute, semantic landmarks. Drop this in every new project before adding anything else.
10m ago 0
Java
Optional — Stop Returning Null
`Optional<T>` makes "may be absent" part of the type signature so callers can't forget the null check. `map`, `orElse`, `ifPresent` chain naturally — no `if (x != null)` boilerplate.
11m ago 0
Python
unique_everseen — Order-Preserving Dedupe
Remove duplicates while preserving original order (set() loses order on collisions). Optional key function lets you dedupe by a derived value — e.g., lowercased email.
11m ago 0
Java
JUnit 5 — Parameterized Tests
`@ParameterizedTest` runs the same test with multiple inputs. Use `@CsvSource`, `@MethodSource`, or `@EnumSource` for data. Eliminates copy-paste in test classes.
11m ago 0
Bash
Trap Signals for Cleanup
Use `trap` to delete temp files / kill background workers when the script exits — even on Ctrl-C or an unhandled error. Single most-undervalued bash feature.
11m ago 0
Java
HttpClient — Synchronous GET (Java 11+)
`java.net.http.HttpClient` ships in the JDK — no Apache HttpClient or OkHttp needed for most cases. Reuse one client across the app; configure timeouts and follow-redirects up front.
11m ago 0
Go
time.Format — The Reference Time
Go's time formatting uses a reference date instead of strftime tokens: `Mon Jan 2 15:04:05 MST 2006` (which is 01/02 03:04:05PM '06 -0700, or 1/2/3/4/5/6/7 — mnemonic). Strange at first, instantly memorable.
11m ago 0
Go
sql.NullString — Nullable DB Columns
Plain `string` can't represent SQL NULL. Use `sql.NullString` (and its siblings `NullInt64`, `NullBool`, etc.) for columns where NULL is a real value distinct from empty.
11m ago 0