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

Showing 361–390 of 770 public snippets

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.
5h 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.
5h ago 0
TypeScript
useFetch — Minimal Data Fetching Hook
A tiny self-contained data-fetching hook with loading/error/data states and AbortController cleanup on unmount. Good baseline before reaching for TanStack Query.
5h ago 0
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.
5h 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.
5h 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.
5h 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.
5h 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.
5h ago 0
Bash
Print a Boxed Banner
Wrap a string in a Unicode box for important headers. Auto-sizes to the longest line. Helps milestone messages stand out in long CI logs.
5h ago 0
Kotlin
repeat, also lateinit and isInitialized
`repeat(n) { i -> ... }` for N-times loops where you don't care about index naming. `lateinit var` lets you declare a non-null var without initializing it — common for DI / framework injection.
5h ago 0
Bash
Confirm Prompt (y/n)
A reusable yes/no prompt with a configurable default and a single-keystroke read. Returns 0 for yes, non-zero for no.
5h ago 0
Kotlin
observable — Listen for Property Changes
`Delegates.observable(initial) { prop, old, new -> ... }` fires a callback every time the property changes. Useful for state-tracking, simple observability without a full reactive lib.
5h ago 0
Bash
Run Command with Timeout
`timeout` (GNU coreutils) kills a command after N seconds. Returns exit code 124 on timeout — let the caller distinguish "timed out" from "failed for other reasons."
5h ago 0
Python
pathlib Quick Reference
Forget os.path.* — pathlib.Path is the modern, OS-aware way to work with paths. Operator overloading for joins, attribute access for components, methods for reads/writes/iterations.
5h ago 0
Go
rate.Limiter — Token-Bucket Rate Limiting
`golang.org/x/time/rate` provides a battle-tested token-bucket limiter. Use to enforce "N requests per second with bursts up to B" — for per-IP throttling, external API rate limits, etc.
5h 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.
5h ago 0
JavaScript
Event Emitter (Pub/Sub)
A lightweight publish/subscribe event system. Listeners register with on(), fire once with once(), are removed with off(), and events are dispatched with emit(). Useful for decoupling modules, building plugin systems, and implementing the Observer pattern without a framework dependency.
5h 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.
5h 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.
5h ago 0
JavaScript
LocalStorage with Expiry
Extends localStorage with TTL (time-to-live) support. setItem stores a value alongside an expiry timestamp. getItem returns null and removes the key if the TTL has elapsed. Useful for caching API responses client-side, storing ephemeral UI state, and implementing remember-me tokens without a backend session.
5h 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.
5h ago 0
JavaScript
Keyboard Shortcut Manager
Registers global keyboard shortcuts with a simple key-combo syntax ("ctrl+k", "meta+shift+p"). Handles modifier keys (ctrl, alt, shift, meta) and prevents default browser behaviour when a shortcut matches. Shortcuts can be unregistered individually or all at once, making it easy to scope shortcuts to page sections or modals.
5h 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.
5h 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.
5h 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.
5h 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.
5h 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.
5h 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.
5h 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"]).
5h 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.
5h ago 0