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.
4h 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.
4h 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.
4h 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.
4h 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.
4h ago 1
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.
15m ago 0
Kotlin
map / filter / reduce
The three classic functional combinators. Each takes a lambda and returns a new collection (or a single value for reduce). Chain freely — intermediate allocations only matter at very large scale (use `Sequence` then).
2h 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.).
3h ago 0
Kotlin
Sequences — Lazy Collections
A `List` materializes every intermediate `map`/`filter` result. A `Sequence` processes ONE element through the whole pipeline at a time — better for big inputs or short-circuiting (`first`, `take`).
3h 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.
3h 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.
4h ago 0
Kotlin
Enums with Properties and Methods
Kotlin enums can carry constructor properties and define methods — including abstract methods overridden per constant. Way more expressive than Java enums.
4h 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.
4h ago 0
Kotlin
groupBy and partition
`groupBy` returns a `Map<Key, List<T>>` keyed by what the lambda returns. `partition` is a special-case `groupBy` for booleans — returns `(matching, nonMatching)` Pair.
4h ago 0
Kotlin
fold and scan
`fold` accumulates from a seed across all items. `runningFold` / `scan` yields every intermediate accumulator value — running totals, cumulative metrics.
4h 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".
4h 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.
4h ago 0
Kotlin
Custom Exception + Sealed Result Pattern
For library / service code, define your own exception hierarchy. Pair with `sealed` + `when` for type-safe error handling at the call site.
4h ago 0
Kotlin
Result Type — Safe Error-Returning APIs
`Result<T>` wraps "success or thrown exception" without forcing the caller into try/catch. `runCatching { ... }` is the standard producer.
4h ago 0
PHP
Recursively Delete Directory
Remove a directory and everything under it. Defensive against symlinks (unlinks the symlink rather than recursing into it). Returns the count of items removed.
4h ago 0
PHP
Convert Camel Case ↔ Snake Case
Convert between camelCase and snake_case identifiers. Handy when mapping JS API responses (camelCase) into PHP database column names (snake_case) and vice versa.
4h ago 0
Kotlin
Infix Functions
A single-arg method/extension can be called without dot or parens when marked `infix`. Lets you write DSL-style code like `5 shouldBe 5` or `key to value`.
4h ago 0
PHP
JSON Structured Logger
Append a single JSON object per line to a log file. Easy to grep and to ship into Datadog / Loki / CloudWatch later without re-parsing.
4h ago 0
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.
4h ago 0
Kotlin
java.time — When You Need JVM Interop
On the JVM, `java.time` is fine — and often necessary for interop with Java APIs. Kotlin's extension methods make it ergonomic enough that you might never reach for kotlinx-datetime.
4h ago 0
PHP
URL-Safe Base64 Encode / Decode
Standard base64 uses + and / which break in URLs. Swap them for - and _, drop the = padding, and you get a string you can put in path segments and query parameters safely.
4h ago 0
PHP
RGB ↔ Hex Conversion
Two-way conversion between #RRGGBB hex strings and [R, G, B] arrays. Handy when working with theme colors that come from both sources (CSS strings vs. RGB sliders).
4h ago 0
PHP
Parse Link Header for Pagination
Parse the standard HTTP Link header (RFC 5988) into a relation → URL map. Lets you follow rel="next" pagination in APIs like GitHub without manually building URLs.
4h ago 0
PHP
Validate Email (RFC-aware)
Use PHP's built-in FILTER_VALIDATE_EMAIL with the FILTER_FLAG_EMAIL_UNICODE flag for IDN domains, plus a length sanity check. Trust this over hand-rolled regex.
4h ago 0
PHP
Validate Uploaded File
A defense-in-depth check for $_FILES uploads: confirms the upload completed, the size is within bounds, the MIME type matches an allow-list (by libmagic, not by extension), and the file landed where PHP expected.
4h ago 0