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

Showing 241–270 of 770 public snippets

PHP
Truncate Text with Ellipsis (word-safe)
Cleanly truncate a string to a max length without breaking words mid-character. Adds a trailing ellipsis when truncated and never exceeds the requested length including the ellipsis.
1h ago 0
PHP
Word Count (UTF-8 aware)
Count words in a string in a way that works for any Unicode script — including those without ASCII whitespace. Built on the \p{L}\p{N} Unicode regex categories.
1h ago 0
PHP
Pluck Column From Array of Rows
Extract a single column from a list of associative arrays into a flat list. Common transformation for SELECT results — equivalent to array_column with optional indexing key.
1h 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.
1h 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.
1h 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.
1h 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.
1h 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.
1h 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.
1h 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.
1h 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.
1h 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.
1h 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.
1h 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.
1h 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.
1h 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.
1h 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.
1h 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.
1h 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"]).
1h ago 0
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.
1h 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.
1h 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.
1h 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.
1h 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.
1h 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.
1h 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.
1h 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.
1h 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.
1h 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.
1h 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.
1h ago 0