Utility
utility
Code Snippets
Chunk an Array into Fixed Sizes
Splitting an array into fixed-size groups is a recurring need for pagination, batch API calls, and grid layouts. This snippet covers a one-line slice loop, a generator variant for streaming large inputs, and the edge cases (size <= 0, non-integer size, non-multiple lengths) that bite production code. Drop it in as a tiny utility and stop reaching for lodash for one helper.
Get Unique Items from an Array
Deduping an array sounds trivial until objects, NaN, and case-insensitive strings show up. This snippet walks from the one-liner everyone reaches for first, to a key-projecting variant that handles object identity, to the gotcha around NaN that catches even seasoned engineers. Pick the version that matches your data shape and keep the rest as reference.
Generate a Numeric Range
JavaScript still has no built-in `range()` like Python, so every codebase eventually grows its own. This snippet shows the canonical `Array.from` trick for `[0, n)`, a `start, end, step` variant that handles negative steps, and a lazy generator for huge ranges where allocating the full array is wasteful. Use it for pagination, retries, table rows, and any test fixture that needs N of something.
Safely Read the Last Element
Reading `array[array.length - 1]` is the line every JavaScript developer writes a thousand times, and a chunk of those calls hide bugs on empty arrays or computed expressions. Modern `Array.prototype.at(-1)` makes the intent obvious and supports negative indexes natively. This snippet shows the modern form, the safe-default helper for empty inputs, and the typed-array story so you pick the right tool.
Group an Array by a Key
Grouping records by a derived key is one of the most common data-shaping tasks in JavaScript: bucketing users by role, orders by status, logs by date. This snippet shows a portable `Map`-based helper, a plain-object variant, and the modern `Object.groupBy` API that landed in Node 22 and recent browsers. It also covers the multi-key composite-key trick for grouping by tuples like `[city, role]`.
Partition an Array by a Predicate
Calling `array.filter(p)` and `array.filter((x) => !p(x))` works but walks the input twice and runs the predicate twice per element, which is wasteful and (for non-pure predicates) plain wrong. A single-pass `partition` returns the matched and unmatched buckets in one go. This snippet covers a clean fold-based implementation, an N-way `partitionBy` for multi-class splits, and a streaming variant that lazily partitions an iterable without materialising the full input.
Zip Multiple Arrays
Python users miss `zip(a, b)` and the Lodash crowd reaches for `_.zip`, but JavaScript can do this cleanly with one helper. This snippet covers the basic two-array zip, an N-array variadic version, the unzip inverse, and a `zipWith` that lets you fold pairs into custom shapes (records, objects, weighted sums). It also clarifies the truncate-to-shortest vs. fill-with-undefined trade-off.
Set Intersection and Difference
Computing the items shared between two arrays, the items in the first but not the second, or the symmetric difference is a routine task: comparing API responses, diffing user selections, finding new vs. removed records. This snippet shows the classic `Set`-backed implementations, an object-aware `byKey` variant, and the new native `Set.prototype.intersection` / `difference` methods that landed in Node 22 and 2024 browsers.
Capitalize the First Letter
Capitalising the first letter of a string is a tiny task that hides several gotchas: empty inputs, multi-word phrases, and Unicode characters whose uppercase form is more than one code unit. This snippet starts with the obvious one-liner, hardens it against `null`/`undefined`/empty strings, then upgrades to a code-point-safe variant and finally a per-word title-case helper. Drop these in for form labels, headings, and CSV column titles.
Convert a String to a URL Slug
Slugifying turns human titles like `"Côte d'Ivoire, 2025!"` into URL-safe segments like `'cote-d-ivoire-2025'`. Done well, it covers Unicode normalization, accent stripping, and edge punctuation; done poorly, it ships duplicate slugs or 404s. This snippet starts with a regex-only baseline, layers in `normalize('NFD')` for diacritics, and ends with a hardened version that collapses dashes and bounds the length.
Truncate Text with an Ellipsis
Truncating overflowing text with `...` keeps card layouts and table cells from breaking, but the naive `slice` approach often cuts mid-word or splits a surrogate pair into garbage. This snippet covers the simple character cap, a word-boundary aware version, and a code-point-correct variant for international content. Use it for previews, tooltips, and any space-bounded label.
Reverse a String Safely
Reversing a string is the textbook one-liner, but the obvious version `[...str].reverse().join('')` corrupts emoji families, flag sequences, and any character with combining marks. This snippet starts with the naive UTF-16 reverse, upgrades to a code-point reverse that fixes surrogate pairs, and ends with `Intl.Segmenter` for true grapheme-cluster correctness. Pick the version that matches the worst-case input you actually expect.
Count Words in a String
Word counting drives reading-time estimates, character-budget warnings, and SEO meta-checks. The naive `str.split(' ').length` overcounts double spaces, miscounts empty input, and ignores non-Latin scripts entirely. This snippet starts with a regex-based whitespace split, hardens it against empty and whitespace-only input, then upgrades to `Intl.Segmenter` for locale-aware counting in Chinese, Japanese, and Thai where there are no spaces.
Escape HTML Special Characters
Inserting user input into HTML without escaping is the canonical XSS vector. The five characters `&<>"'` cover most rendering contexts, but attribute values, URL attributes, and `<script>` blocks each have stricter rules. This snippet starts with the minimal map every JS dev should memorise, adds an attribute-safe variant that also escapes the backtick, and ends with a note on when to reach for a real sanitiser like DOMPurify (without bundling it).
Pick a Subset of Object Keys
Picking a whitelist of fields from an object is a daily chore for API responses, form submissions, and analytics events. This snippet covers the canonical Object.fromEntries filter, a typed-friendly variant that drops missing keys, and a generic helper that picks by predicate. Stop hand-rolling it for every endpoint and reach for the version that fits your data.
Omit Keys from an Object
Stripping a few sensitive or transient keys before logging, persisting, or returning an object is the inverse of `pick` and just as common. This snippet covers the rest-destructuring one-liner for fixed key sets, an iterative version for dynamic blacklists, and a deep variant that walks nested objects. Pick whichever fits your data shape and keep the others as reference.
Map Over an Object's Values
JavaScript objects have no built-in `mapValues` like Ramda or Underscore, so every codebase eventually grows its own. This snippet covers the canonical `Object.fromEntries` transform, a sibling `mapKeys` for renaming, and a combined version that lets you reshape both keys and values in one pass. Use them to coerce types, format display strings, or normalise API payloads in a few lines.
Check if an Object is Empty
Checking whether an object has any keys is one of those `if (!obj)` traps that bites every JavaScript codebase. This snippet covers the canonical short-circuit, the reason `Object.keys().length === 0` works, and an `isEmpty` helper that handles arrays, strings, Maps, Sets, and plain objects in one pass. Drop it next to your other guards so empty checks stop returning surprises.
Deep Clone with structuredClone
Deep cloning is no longer a `JSON.parse(JSON.stringify(x))` hack. Modern runtimes ship `structuredClone`, which handles cycles, Maps, Sets, typed arrays, and Date out of the box. This snippet shows the canonical built-in usage, the JSON fallback for legacy code paths and its real limits, and a hand-rolled recursive clone for when you need to skip specific keys or types. Pick the right tool and stop carrying lodash for one helper.
Deep Merge Two Objects
Layering a defaults object under a user override is a daily need for config files, theme tokens, and React props, but `Object.assign` and spread only do shallow merges. This snippet walks from a recursive deep merge that follows nested plain objects, to an array-strategy variant that lets the caller pick concat vs replace, to a variadic version that folds an arbitrary number of layers from defaults to overrides.
Get a Nested Value by Path
Optional chaining handles statically-known paths, but dynamic dotted strings like `'user.address.city'` or `'items[0].id'` still need a resolver. This snippet walks from the simple dot-only `get`, to a path parser that understands bracket notation and array indices, to a sibling `set` that creates intermediate containers safely. Use them whenever a path comes from config, JSONPath-lite, or a CMS field.
Deep Structural Equality Check
Comparing two values structurally is a deceptively hard problem: `===` only checks reference, `JSON.stringify` reorders keys and drops undefined, and naive recursion stack-overflows on cycles. This snippet builds up the comparator step by step: a baseline that handles primitives and plain objects, a typed-aware version that respects Date / RegExp / Map / Set, and a cycle-safe production-grade implementation. Use the version that matches your data shape.
Debounce Function in JavaScript
Debouncing collapses a burst of calls into a single trailing invocation, which is the standard fix for noisy events like keystrokes, resize, and scroll. This snippet covers the canonical trailing-edge debounce, a variant with a manual `cancel` for component unmount, and a Promise-returning version that resolves only with the last call's result. Drop it into any UI handler that fires faster than the work it triggers.
Throttle Function in JavaScript
Throttling caps how often a function can fire to at most once per interval, which is the right tool for scroll, mousemove, and analytics beacons. This snippet contrasts throttle against debounce, then walks from a leading-edge timestamp gate to a `setTimeout`-driven version that includes a manual `cancel`. Pick the variant that matches whether the very first call should fire immediately.
Run a Function Only Once
Wrapping a function so it runs at most once is the right tool for one-shot initialisers, lazy connection setup, and event handlers that must not double-fire. This snippet covers the canonical `once`, an async-aware version that caches the in-flight Promise, and a `resetOnce` variant for tests and feature flags. Drop it next to your event listeners and stop guarding with ad-hoc booleans.
Memoize Higher-Order Function
Memoization caches function results keyed by arguments so repeat calls return in O(1). This snippet covers the canonical single-arg memoize, a multi-arg version that handles object identity via a `Map` chain, and an LRU-bounded variant that prevents unbounded cache growth. Use it for pure functions whose work dwarfs the lookup cost (parsing, layout calc, recursive DP).
Curry a Function in JavaScript
Currying turns a multi-argument function into a chain of single-argument calls so you can pre-bind some arguments and pass the rest later. This snippet covers the variadic curry every codebase reaches for, a placeholder-aware version for skipping argument positions, and a typed-friendly fixed-arity helper for stricter call shapes. Use it for partial application and to build small DSLs.
Compose and Pipe Helpers
Composing small functions into a single transformation is the bread and butter of functional pipelines. This snippet contrasts the right-to-left `compose` (math notation) with the left-to-right `pipe` (data-flow notation), then shows an async-aware `pipeAsync` for chained `await`-able steps. Use them to flatten nested calls into a readable left-to-right (or right-to-left) sequence.
Retry with Exponential Backoff
Network calls and flaky integrations need a retry wrapper, but plain retries hammer the same endpoint and amplify outages. Exponential backoff doubles the wait between attempts so transient failures recover fast and persistent failures don't DDoS the upstream. This snippet covers the canonical retry, a jittered version that prevents thundering-herd retries across clients, and a policy-driven variant that lets the caller decide which errors are retryable.
Throttle with Leading and Trailing Edges
A leading-only throttle drops the last call's arguments; a trailing-only throttle feels laggy on the first event. The Lodash-style throttle that fires on BOTH edges is the version every UI codebase eventually wants: an immediate response on the leading edge plus a guaranteed final fire after the burst ends. This snippet builds that production-grade throttle from scratch with cancel and flush, then shows the configurable `leading` / `trailing` toggle that powers most real-world helpers.
Sleep with a Promise
Pausing async code is a one-line problem until you need cancellation, a typed signal, or to reuse the helper across files. This snippet starts with the canonical `setTimeout` Promise wrapper, then adds `AbortSignal` support so callers can cancel waits cleanly. Drop it into any toolkit and stop reaching for `setTimeout` callbacks in async functions.
Timeout a Promise
A promise that never settles will leak handles and stall UI flows; wrapping it with a deadline turns a bug into a recoverable error. This snippet shows the classic `Promise.race` pattern, then upgrades it to clean up the timer on success and to forward an `AbortSignal` so cancelled work stops doing real I/O. Use it around any `fetch`, DB call, or third-party SDK that does not expose a native timeout option.
Run Async Functions in Sequence
`Promise.all` runs every task at once, but sometimes you need strict ordering: a write that must come after a read, a paginated API that uses the previous response as a cursor, or a queue of migrations that must not interleave. This snippet covers the serial `for...of` loop, the equivalent `reduce`-based one-liner, and a chain helper that pipes each result into the next step. Pick the shape that matches how your data flows.
Partition allSettled Results
`Promise.allSettled` is the right call for partial-success workflows, but its `{ status, value, reason }` shape is awkward to consume directly. This snippet wraps it with a partitioner that returns `{ values, errors }` so the happy path stays simple, then layers in input-aware error reports that pair each failure with the original argument. Use it for fan-out fetches, batched writes, or any spot where one bad item should not poison the whole batch.
Poll Until a Condition Is True
Polling shows up everywhere systems are eventually consistent: waiting for a job status to flip to `done`, for a file to appear, for a deploy to roll out. This snippet walks from a basic fixed-interval poller to one with a deadline, then to exponential backoff with jitter so a thundering herd does not hammer the upstream. Reach for it any time you need to wait for a remote condition without writing the same retry loop again.
Cancellable fetch with AbortController
Every modern UI eventually needs to cancel in-flight requests: a search box that fires on every keystroke, a route change that abandons a partially loaded page, a tab close that should free sockets. `AbortController` is the standard primitive for this. This snippet covers the minimal abort pattern, a `fetchWithTimeout` helper that aborts on a deadline, and a hook-friendly cleanup pattern that pairs each request with its own controller.
Clamp a Number Within a Range
Clamping a value into `[min, max]` shows up in scroll math, slider components, RGB arithmetic, and clamping pagination cursors. The one-liner is trivial, but the helpful version handles swapped bounds, `NaN`, and integer-only callers. This snippet covers the simple form, an `inclusive`/`exclusive` mapping flag, and an integer variant that snaps to whole numbers in the range.
Format Bytes as a Human String
Showing `1457280 bytes` is hostile UX; showing `1.39 MB` (or `1.46 MB` if you use SI) is what users expect. This snippet covers the binary IEC variant (KiB, MiB, GiB), the decimal SI variant (KB, MB, GB), and a configurable helper that picks the unit, precision, and separator. Use it for upload progress, storage dashboards, or anywhere a raw byte count would otherwise leak into the UI.
Random Integer in a Range
Off-by-one bugs in random integer helpers are the silent kind: tests pass, distributions look right, but the maximum value never appears. This snippet covers the inclusive `[min, max]` form most people actually want, the unbiased version using `crypto.getRandomValues`, and a helper for picking a uniform random element from an array. Use it for sampling, dice rolls, jitter, and quick demos.
Copy Text to the Clipboard
Every dashboard, share modal, and code-block UI eventually needs a copy button. The modern path is `navigator.clipboard.writeText`, but it requires a secure context and a user gesture, so a robust helper falls back to a hidden `<textarea>` when the API is unavailable. This snippet covers the modern call, the legacy fallback, and a copy-with-toast helper that wraps both behind a single async function.
Read a URL Query Parameter
Reading `?q=hello` is a one-liner with `URLSearchParams`, but the helpers around it (multi-value params, defaults, type coercion, updating without reload) are where most apps end up duplicating code. This snippet covers the basic read, a typed-default helper, and a setter that updates the URL with `history.replaceState` so the back button keeps working. Use it for filters, search inputs, and shareable links.
Trigger a File Download from a Blob
Generating a CSV, JSON export, or screenshot client-side and saving it without a server round-trip is a five-line trick: build a `Blob`, mint an object URL, click a hidden `<a download>`, and revoke the URL. This snippet covers the canonical helper, a JSON export wrapper, and the cleanup pattern that prevents memory leaks during long-running sessions.
Check if an Element Is in the Viewport
Lazy-loading images, animating sections on enter, and infinite scroll all start with the same question: is this element on screen? The classic answer was a scroll handler plus `getBoundingClientRect`, but `IntersectionObserver` is now the right tool: passive, batched, and rate-limited by the browser. This snippet covers the synchronous bounds check, the async observer-based watcher, and a one-shot helper that resolves once a target enters the viewport.
Tiny Pub/Sub Event Bus
When two parts of your app need to talk without a direct reference (a Zustand store telling the toaster, a service worker pushing to the UI), a tiny pub/sub bus is often cleaner than threading callbacks. This snippet builds a minimal `on/off/emit` bus, adds a `once` shorthand, and shows the typed channels pattern that scales to a real codebase. Drop it in next to your state library.
isDefined Type Guard
Filtering an array of `(T | undefined)[]` should leave you with `T[]`, but `Array.prototype.filter(Boolean)` leaves the type as `(T | undefined)[]` because the compiler does not understand the predicate. A user-defined type guard with the `value is T` return type fixes the inference. This snippet covers the basic `isDefined`, an `isNonNullable` variant that also drops `null`, and a generic `compact` that uses the guard to narrow at the array level.
React useToggle Hook
Boolean state shows up everywhere: modals, drawers, accordions, password visibility, dark mode. The useToggle hook collapses three lines of `useState` plus a setter into one call. This snippet covers the minimal toggle, a value-aware variant that lets callers pin the state to a specific boolean, and an enum-aware version that cycles through any number of states (light / dark / system).
Community
Why I Stopped Mocking `fetch` and Reached for MSW
The two-handler MSW setup I drop into every Vitest project. Pattern-matched URL routing, typed JSON responses, and per-test overrides without re-importing the server.
The pytest Fixture Builder I Cannot Live Without
A four-stage tour of the fixture-builder pattern: a callable factory that mints test models with sensible defaults, layered overrides, deterministic IDs, and per-test isolation. The shape I paste into every conftest.py.
The Fetch Wrapper I Keep in Every Project
My zero-dep `apiFetch` for Node and the browser. Adds a per-request timeout, retries with jittered backoff on 5xx and network failures, parses JSON, and attaches an auth token without leaking it into errors.
The tcpdump One-Liner I Actually Remember
A small Python wrapper around the only tcpdump invocation I can recall under pressure, plus a parser that turns its line-buffered output into JSON so I can pipe it to jq.
The 30-Line Debug Print I Keep in My Dotfiles
A pretty-printer for Python objects that I paste into every new project. Shows types, depth, and truncates long containers, so I stop reaching for `pprint` mid-incident.
Resolving a Production Stack Trace Against a Source Map
When a minified Sentry stack only points at `bundle.js:1:140183`, this is the zero-dep VLQ decoder I drop in to map every frame back to a real source line.
useLatest Ref: The Anti-Stale-Closure Pattern
The five-line hook I reach for whenever an effect, a setTimeout, or an external subscription needs to call back into the latest value of a prop or state without re-binding.
Signed URL Generator With HMAC
The 60-line HMAC-signed URL helper I use for download links and webhook callbacks. Stdlib only, constant-time verification, expiry baked in, and no S3 dependency to debug at 2 a.m.
How I Stopped My Jest Snapshots From Churning
A serializer that strips dates, ids, and request hashes out of snapshot JSON so a fresh git clone does not nuke the snapshot diff. Drop into `snapshotSerializers` and forget.
A File Drop Zone Without a Library
The drop zone I keep instead of pulling in react-dropzone (60+kB minified): drag-over visuals, multi-file drops, folder uploads via DataTransferItem, and the Safari quirk where dragleave fires on every child enter.
useUndoRedo Hook With Bounded History
The custom hook I drop in whenever an editor screen needs cmd+z. Gives you `undo`, `redo`, `set`, and a hard cap on memory so a long session does not balloon the heap.
