Tags

Code Template

Code Template

0 lessons
95 code snippets
31 community items

code-template

Code Snippets

95 snippets
Code Snippet

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.

JavaScript
arrays
utility
code-template
array-manipulation-patterns

544

17

Easy
Code Snippet

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.

JavaScript
arrays
utility
set
code-template

468

12

Easy
Code Snippet

Flatten a Nested Array

Flattening a nested array is a one-line job most of the time, but pre-built `Array#flat` is shallow by default and the depth parameter has surprises. This snippet starts with the modern built-in, adds a recursive deep-flatten that works in any environment, and ends with the iterative stack version that avoids stack-overflow on pathological inputs. Three flavours, one mental model.

JavaScript
arrays
recursion
code-template
array-manipulation-patterns

410

4

Easy
Code Snippet

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.

JavaScript
arrays
utility
generators
code-template

1.1k

14

Easy
Code Snippet

Shuffle an Array (Fisher-Yates)

The naive `array.sort(() => Math.random() - 0.5)` looks fine until you measure it: the distribution is heavily biased and some pairs swap with much higher probability than others. The Fisher-Yates shuffle is the standard correct answer in O(n) time with uniform output. This snippet shows the in-place version, a non-mutating wrapper, and an empirical demo of why the popular `sort`-based trick is biased.

JavaScript
arrays
code-template
array-manipulation-patterns

1k

7

Easy
Code Snippet

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.

JavaScript
strings
utility
code-template

454

12

Easy
Code Snippet

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.

JavaScript
strings
utility
code-template

1.1k

12

Easy
Code Snippet

Tiny Template String Formatter

Sometimes you need a templating helper that does not pull in handlebars or eta, just enough to substitute `{name}` placeholders against a values object. This snippet starts with a 5-line interpolator, adds escape support so literal braces survive, and ends with a tagged-template-literal version that gives you compile-time placeholder safety. Drop it into i18n strings, log formatters, or email subject lines.

JavaScript
strings
regex
js-template-literals
code-template

428

14

Medium
Code Snippet

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.

JavaScript
utility
code-template
js-spread-rest

245

2

Easy
Code Snippet

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.

JavaScript
utility
code-template
js-spread-rest

389

9

Easy
Code Snippet

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.

JavaScript
utility
code-template
functional-programming

813

11

Easy
Code Snippet

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.

JavaScript
utility
code-template

664

18

Easy
Code Snippet

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.

JavaScript
utility
code-template
immutability

325

6

Medium
Code Snippet

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.

JavaScript
utility
code-template
recursion

489

7

Medium
Code Snippet

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.

JavaScript
utility
code-template
js-optional-chaining

681

5

Medium
Code Snippet
Premium

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.

JavaScript
utility
code-template
recursion

401

7

Hard
Code Snippet

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.

JavaScript
utility
code-template
performance-optimization
throttling

615

17

Easy
Code Snippet

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.

JavaScript
utility
code-template
performance-optimization
rate-limiting

800

17

Easy
Code Snippet

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.

JavaScript
utility
code-template
idempotency

876

22

Easy
Code Snippet

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).

JavaScript
utility
code-template
memoization
higher-order-functions

458

7

Medium
Code Snippet

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.

JavaScript
utility
code-template
currying
functional-programming

699

3

Medium
Code Snippet

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.

JavaScript
utility
code-template
composition
functional-programming

954

16

Medium
Code Snippet

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.

JavaScript
utility
code-template
error-handling
retry-policy

855

15

Medium
Code Snippet
Premium

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.

JavaScript
utility
code-template
performance-optimization
rate-limiting

158

5

Hard
Code Snippet

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.

JavaScript
async-programming
promises
utility
code-template

238

5

Easy
Code Snippet

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.

JavaScript
async-programming
promises
utility
code-template

273

8

Medium
Code Snippet

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.

JavaScript
math
utility
code-template

199

4

Easy
Code Snippet

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.

JavaScript
math
utility
code-template

399

6

Easy
Code Snippet

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.

JavaScript
js-web-apis
js-dom
utility
code-template

290

4

Easy
Code Snippet

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.

JavaScript
js-web-apis
js-dom
utility
code-template

415

12

Easy
Code Snippet

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.

JavaScript
observer-pattern
event-driven
utility
code-template

941

18

Medium
Code Snippet

DeepPartial Utility Type

`Partial<T>` only flips the top-level keys to optional, which is rarely enough for nested config or patch-style update payloads. `DeepPartial<T>` walks the type tree and makes every key at every depth optional. This snippet builds the basic recursive form, refines it for arrays and tuples so they are not flattened to objects, and pairs it with a deep-merge helper that consumes the type cleanly.

TypeScript
ts-utility-types
ts-mapped-types
ts-conditional-types
code-template

401

11

Easy
Code Snippet

ValueOf Utility Type

`keyof` gives you the union of property names; `ValueOf<T>` gives you the union of property values. Combined with `as const` it derives a string-literal union from a single source-of-truth object, so the runtime constant and the static type can never drift. This snippet covers the one-line definition, an enum-replacement pattern, and a discriminator helper that drives type-safe `switch` blocks.

TypeScript
ts-utility-types
ts-mapped-types
ts-generics
code-template

1.1k

25

Easy
Code Snippet

DeepReadonly Utility Type

`Readonly<T>` only freezes the top level, which is rarely enough for state objects passed across module boundaries. `DeepReadonly<T>` walks the type tree and marks every property `readonly` at every depth. This snippet builds the recursive form, refines it for arrays so they become `ReadonlyArray<T>`, and pairs it with `Object.freeze` so the runtime matches the type-level guarantee.

TypeScript
ts-utility-types
ts-mapped-types
ts-conditional-types
code-template

501

9

Medium
Code Snippet

Branded (Nominal) Types

TypeScript is structurally typed, so `type UserId = string` and `type OrderId = string` are interchangeable to the compiler, which is exactly the bug class you want to prevent. Branded (nominal) types attach a phantom tag so the two stay distinct at compile time without any runtime cost. This snippet covers the basic brand pattern, a parser-style smart constructor that produces a brand from a raw value, and a multi-brand domain model that ties them together.

TypeScript
ts-utility-types
ts-type-narrowing
ts-generics
code-template

705

20

Medium
Code Snippet

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.

TypeScript
ts-type-guards
ts-type-narrowing
utility
code-template

916

6

Easy
Code Snippet

Exhaustive assertNever Switch

Discriminated unions are TypeScript's superpower for state machines, redux reducers, and API response shapes, but a `switch` over them silently goes stale the moment a new variant appears. The `assertNever` helper flips silent staleness into a compile error: any unhandled branch means the type passed in is not actually `never`. This snippet covers the helper, a reducer that uses it for compile-time safety, and an interim `default` strategy for production safety while you iterate.

TypeScript
ts-type-guards
ts-type-narrowing
ts-conditional-types
code-template

894

14

Easy
Code Snippet

Infer a Type from a Zod Schema

Maintaining a Zod runtime schema and a TypeScript interface that match by hand is a maintenance trap: every field change has to be edited twice. `z.infer<typeof Schema>` derives the static type from the schema, so the schema is the single source of truth. This snippet covers the basic infer pattern, the input/output split for transforms, and a typed parsing wrapper that turns runtime errors into a clean `Result` shape.

TypeScript
ts-utility-types
ts-type-guards
ts-generics
code-template

979

17

Medium
Code Snippet

Fixed-Length Tuple via Generics

Constraining an argument to 'an array of exactly 4 numbers' is a common need (RGBA, 4x4 matrices, fixed-length feature vectors). TypeScript can express it with a recursive `TupleOf<T, N>` that builds up `[T, T, T, ...]` of the requested length. This snippet covers the recursive construction, a runtime helper that produces a value matching the type, and a length-comparison variant useful for richer constraints ("at least N", "between N and M").

TypeScript
ts-utility-types
ts-conditional-types
ts-generics
code-template

562

15

Medium
Code Snippet

React useDebounce Hook

Debouncing a fast-changing value (a search input, a window resize, a slider) is one of the first React-specific utilities every project needs. This snippet shows the simplest one-state useDebounce hook, a leading-edge variant for instant first reactions, and a useDebouncedCallback variant that wraps a function instead of a value. Pick the shape that matches what your component actually needs.

JavaScript
react
hooks
performance-optimization
code-template

220

7

Easy
Code Snippet

React useThrottle Hook

Throttling caps the rate at which a value updates while still letting changes through at a steady cadence. This snippet covers the basic useThrottle that emits at most once per window, a useThrottledCallback variant for wrapping functions, and the leading-plus-trailing edge form that keeps the first and last events without dropping the tail. Use it for scroll handlers, mouse trackers, and any high-frequency stream you need to sample.

JavaScript
react
hooks
performance-optimization
code-template

927

5

Easy
Code Snippet

React useLocalStorage Hook

Persisting a piece of state to localStorage so it survives a page reload is one of the most-requested custom hooks. This snippet covers the basic JSON-serialised hook, an SSR-safe variant that lazily reads only on the client, and a cross-tab sync version that listens for the storage event. Pick the one that matches whether your app is client-only, server-rendered, or multi-window.

JavaScript
react
hooks
js-local-storage
code-template

496

4

Easy
Code Snippet

React usePrevious Hook

Tracking the previous value of a prop or piece of state lets you diff renders, animate transitions, and detect specific change patterns. This snippet shows the canonical one-liner usePrevious, a useChanged variant that returns whether the value just changed, and a useHistory hook that keeps the last N values for undo / redo. All three are tiny but easy to get subtly wrong.

JavaScript
react
hooks
code-template
references

203

6

Easy
Code Snippet

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).

JavaScript
react
hooks
code-template
utility

630

16

Easy
Code Snippet

React useIsMounted Hook

Setting state on an unmounted component throws a warning in development and can mask real bugs in production. The useIsMounted hook gives async callbacks a way to bail out before they touch React state. This snippet covers the basic ref-based hook, a useSafeState wrapper that no-ops after unmount, and a useSafeCallback variant that protects the function itself.

JavaScript
react
hooks
code-template
references

656

14

Easy
Code Snippet

React useInterval Hook (Dan Abramov pattern)

Calling setInterval inside useEffect breaks the moment the callback closes over stale state. Dan Abramov's useInterval pattern stores the latest callback in a ref so the timer always fires the freshest version without resetting. This snippet covers the canonical pattern, a pause-aware variant that accepts a null delay, and a useTimeout sibling for one-shot timers.

JavaScript
react
hooks
code-template
performance-optimization

1.1k

33

Medium
Code Snippet

React useEventListener Hook

Manually attaching DOM event listeners inside useEffect is repetitive and easy to misuse: forgotten cleanups leak handlers, and stale callbacks see old state. The useEventListener hook centralises the pattern so consumers just declare which event they care about. This snippet covers the basic window listener, a target-aware variant that supports any element ref, and a typed signature that picks the right event payload.

JavaScript
react
hooks
code-template
js-event-loop

364

1

Medium
Code Snippet

React useClickOutside Hook

Dropdowns, popovers, and modals all need to dismiss when the user clicks outside their wrapper. The useClickOutside hook centralises the listener wiring so feature components stay declarative. This snippet covers the pointerdown-based version, an ignore-list variant for portal triggers, and the keyboard escape sibling that completes the dismissal pattern.

JavaScript
react
hooks
code-template
js-event-loop

269

6

Medium
Code Snippet

React useMediaQuery Hook

Mirroring CSS media queries inside React components keeps logic about responsive breakpoints, dark-mode preference, and reduced motion in one place. The useMediaQuery hook subscribes to a MediaQueryList so renders stay in sync with the browser. This snippet covers the basic match boolean, an SSR-safe variant with an initial fallback, and a useBreakpoint helper that maps named breakpoints onto Tailwind-style logic.

JavaScript
react
hooks
code-template
css-media-queries

720

5

Medium
Code Snippet

React useCopyToClipboard Hook

A copy-to-clipboard button needs to do three things: write to the clipboard, surface success or failure to the UI, and reset the success indicator after a short delay. This snippet covers a status-aware hook with a one-shot success flag, a fallback variant for older browsers, and a copy-with-format helper that writes both plain text and rich HTML. Drop it next to any 'Copy code' button.

JavaScript
react
hooks
code-template
js-web-apis

803

21

Medium
Code Snippet
Premium

React useFetch Hook with Cancellation

Building a useFetch from scratch teaches the pieces every data-fetching library has to solve: tracking loading and error state, cancelling in-flight requests when the URL changes, and ignoring stale responses after the component unmounts. This snippet covers the canonical AbortController-based hook, a generation-counter variant that protects against race conditions when AbortController is unavailable, and a mutate refetch helper for manual revalidation.

JavaScript
react
hooks
code-template
js-fetch-api

1k

31

Hard
Code Snippet
Premium

React useInfiniteScroll Hook

Infinite scroll feels simple until you wire IntersectionObserver, page tracking, and the request lifecycle together. This snippet covers a sentinel-ref hook that fires a load callback when the bottom marker scrolls into view, a paginated variant that tracks the page state for you, and an end-of-feed guard that stops calling the callback once the server says there is no more data.

JavaScript
react
hooks
code-template
performance-optimization

354

1

Hard
Code Snippet

CSS Grid Responsive Layout Snippet

A responsive card grid that fills as many columns as fit and never produces an awkward last row is a one-line CSS Grid trick. This snippet covers the canonical `auto-fill` plus `minmax` recipe, the `auto-fit` variant that collapses empty tracks, and a row-spanning variant for masonry-like layouts. No media queries, no JavaScript.

CSS
css-selectors
css-grid
css-responsive-design
code-template

458

15

Easy
Code Snippet

Center Anything with Flexbox

Centering a child horizontally and vertically used to require pixel math, table tricks, or absolute-positioning hacks. Flexbox collapses the whole thing into three properties. This snippet covers the canonical centering pattern, the inline-flex variant for centering inside button-shaped wrappers, and the gap-aware multi-child version that keeps spacing consistent.

CSS
css-selectors
css-flexbox
css-alignment
code-template

258

5

Easy
Code Snippet

Truncate Text with Ellipsis

Single-line text truncation is one of the most common UI requirements: titles, table cells, breadcrumbs. Done wrong, the text wraps or overflows. Done right, it shrinks with a clean ellipsis. This snippet covers the three-line single-line recipe, an inline variant that needs `min-width: 0` inside flex parents, and a tooltip-friendly version that exposes the full text on hover.

CSS
css-selectors
css-overflow
code-template
cheat-sheet

808

20

Easy
Code Snippet

Accessible Skip-to-Content Link

A skip-to-content link lets keyboard and screen-reader users jump past the navigation straight to the main content. Most sites get the markup right but hide it permanently with `display: none`, which screen readers also skip. This snippet covers the visually-hidden-until-focus pattern, the matching CSS to keep it usable, and the required `<main>` target so the link actually works.

HTML
html-elements
accessibility
html-accessibility
code-template

989

13

Easy
Code Snippet

Responsive Image with picture

Serving the right image at the right size saves bandwidth on phones and avoids blurry assets on retina displays. The `<picture>` element plus `srcset` lets the browser pick the best source for the device. This snippet covers density-based srcset for retina, width-based srcset with sizes for fluid layouts, and art direction with multiple `<source>` entries for different aspect ratios.

HTML
html-elements
html-responsive
html-media
code-template

995

5

Easy
Code Snippet

Multi-line Text Truncation

Single-line truncation is solved with `text-overflow: ellipsis`, but truncating to N lines requires the WebKit line-clamp API. This snippet covers the standard three-line ellipsis using the modern `line-clamp` shorthand, the older `-webkit-line-clamp` form for broader support, and a JS-free fade-out variant for browsers without line-clamp.

CSS
css-selectors
css-overflow
code-template
cheat-sheet

585

13

Medium
Code Snippet

Sticky Footer with Flexbox

A footer that stays at the bottom of the viewport on short pages and at the bottom of the content on long pages used to require absolute positioning, fixed heights, or table-cell tricks. Flexbox solves it with two declarations. This snippet covers the canonical body-flex layout, the grid-based equivalent, and the wrapper variant for apps that already have a top-level container.

CSS
css-selectors
css-flexbox
css-grid
code-template

505

7

Medium
Code Snippet

Dark Mode with CSS Variables

Implementing dark mode without a heavy theming library comes down to a stable token contract and a media query. This snippet covers the system-preference dark mode using `prefers-color-scheme`, a class-based override that lets users opt in or out, and a per-component theme that nests tokens for a single section.

CSS
css-selectors
css-variables
css-media-queries
code-template

580

9

Medium
Code Snippet

Accessible Semantic Form Markup

A login or signup form is the highest-traffic interaction on most apps, and getting the semantic markup right pays dividends in screen-reader support, autofill quality, and form validation. This snippet covers a labelled email-and-password form, a form-with-error-summary using `aria-describedby`, and a multi-step fieldset pattern for grouped inputs.

HTML
html-elements
html-forms
accessibility
code-template

599

6

Medium
Code Snippet
Premium

Component-Aware Container Queries

Media queries respond to viewport size, but components do not always live at viewport scale: a card might render in a sidebar at 240px or in a feature row at 800px. Container queries let a component style itself based on its own width. This snippet covers the basic `@container` rule, the size container with named breakpoints, and the style container variant for theming children based on parent state.

CSS
css-selectors
css-responsive-design
css-media-queries
code-template

819

20

Hard
Code Snippet

Binary Search Template

Binary search is the most asked algorithm in interviews and the easiest to get wrong: off-by-one bugs, infinite loops, integer overflow on the midpoint. This snippet covers the iterative bounds template that always terminates, a recursive variant for contrast, and a found-or-insertion-point version that returns where the value would go if absent. The same skeleton powers the lower-bound and upper-bound variants in the next entry.

JavaScript
algorithms
binary-search
code-template
two-pointers

967

17

Easy
Code Snippet

Two-Pointer Template

The two-pointer technique is the linear-time answer to many sorted-array problems: pair sums, palindrome checks, in-place reversal, partition. This snippet covers the opposite-ends sweep for sorted-pair targets, the reverse-in-place pattern, and the slow-fast pointer used for in-place mutation. Each fits in 10 lines and runs in O(n) time, O(1) extra space.

JavaScript
algorithms
two-pointers
code-template
arrays

418

3

Easy
Code Snippet

Sliding Window Template

Sliding window is the linear-time alternative to nested loops for substring-and-subarray problems. This snippet covers the fixed-size window for max-sum-of-k, the variable-size window for longest-substring-with-condition, and the at-most-K shrinkable form that handles 'at most / exactly K distinct' problems with one trick.

JavaScript
algorithms
sliding-window
code-template
two-pointers

994

12

Easy
Code Snippet

Stack via Array

JavaScript does not ship a dedicated `Stack` class because `Array` already supports O(1) `push` and `pop`. This snippet covers the array-as-stack idiom, a tiny class wrapper for self-documenting code, and a balanced-parentheses checker that demonstrates the canonical stack-driven algorithm. Use this template anywhere the LIFO order matters: undo, expression evaluation, DFS bookkeeping.

JavaScript
data-structures
stack
code-template
arrays

402

8

Easy
Code Snippet

Lower-Bound and Upper-Bound Binary Search

Lower-bound and upper-bound binary search are the two primitives every other range query depends on. Lower-bound returns the first index where a value could be inserted; upper-bound returns the first index strictly greater than the value. This snippet covers both forms, then composes them to count occurrences in a sorted array in O(log n).

JavaScript
algorithms
binary-search
code-template
two-pointers

1.1k

34

Medium
Code Snippet

Singly Linked List Template

Linked lists rarely beat arrays in production JavaScript, but they are the single most-asked interview data structure and the conceptual foundation for skip lists, LRU caches, and queue implementations. This snippet covers the Node + List skeleton with O(1) prepend, an O(n) traversal helper, and the in-place reverse that shows up in nearly every interview round.

JavaScript
data-structures
linked-list
code-template
algorithms

1.1k

16

Medium
Code Snippet

Doubly Linked List Template

A doubly linked list adds a `prev` pointer to every node, which unlocks O(1) removal of a known node and O(1) traversal in both directions. This is the structural backbone of LRU caches, browser back / forward stacks, and skip-list-adjacent designs. This snippet covers the Node + List skeleton with sentinel head and tail, the unlink-known-node operation that makes LRU possible, and a forward / backward iteration helper.

JavaScript
data-structures
linked-list
code-template
algorithms

256

7

Medium
Code Snippet

BFS Traversal Template

Breadth-first search visits every reachable node in non-decreasing distance from the start, which makes it the right algorithm for shortest-path-in-unweighted-graph, level-order tree traversal, and grid-flood problems. This snippet covers the canonical queue + visited skeleton, the level-by-level form for tree-style problems, and the multi-source variant for problems like 'rotting oranges' where many start points share a frontier.

JavaScript
algorithms
bfs
code-template
queue

1.1k

29

Medium
Code Snippet

DFS Traversal Template

Depth-first search visits a node, then recursively visits each unvisited neighbor before backtracking. It is the natural traversal for tree problems, cycle detection, topological order, and connected-components. This snippet covers the recursive form, an iterative stack-based form for very deep graphs, and a path-tracking variant that surfaces the actual route from start to a target.

JavaScript
algorithms
dfs
code-template
stack

180

5

Medium
Code Snippet

Trie Implementation in JavaScript

A trie (prefix tree) supports insert, exact-match search, and prefix-search in O(L) where L is the word length, regardless of how many words are stored. This makes it the right structure for autocomplete, spell-check, and IP-routing tables. This snippet covers a Map-backed trie with insert and search, the startsWith prefix scan that powers autocomplete, and a wordsWithPrefix collector that returns every match.

JavaScript
data-structures
trie
code-template
strings

769

14

Medium
Code Snippet

Min-Heap Template

JavaScript still has no built-in priority queue, so most real-world code rolls its own min-heap. This snippet covers a generic comparator-based heap with push and pop, the sift-up and sift-down internals that make both O(log n), and a heapify-from-array helper that builds a heap from an arbitrary input in O(n).

JavaScript
data-structures
heap
code-template
algorithms

588

5

Medium
Code Snippet

LRU Cache (Map-Backed)

An LRU (Least Recently Used) cache evicts the entry that has been untouched the longest when capacity overflows. The trick that makes both `get` and `put` O(1) is JavaScript's `Map` preserving insertion order. This snippet covers the Map-backed implementation, an explicit doubly-linked-list version that mirrors what other languages need, and a TTL-aware variant that evicts entries that are too old.

JavaScript
data-structures
lru-cache
code-template
hash-table

263

4

Medium
Code Snippet
Premium

Disjoint Set (Union-Find) Template

Disjoint Set Union (DSU) tracks a partition of N elements into disjoint groups, supporting near-constant-time `find` (which group?) and `union` (merge two groups). It is the building block for Kruskal's MST, connected components on dynamic graphs, and the redundant-connection problem. This snippet covers the parent-array skeleton, the path-compression optimisation that flattens trees on every find, and the union-by-rank merge that keeps trees shallow.

JavaScript
data-structures
union-find
code-template
algorithms

710

21

Hard
Code Snippet
Premium

Dijkstra Shortest Path Template

Dijkstra's algorithm finds the shortest path from a source to every reachable node in a weighted graph with non-negative edge weights. The textbook O((V + E) log V) implementation pairs a min-heap with a relaxation loop. This snippet covers the heap-based template, a parent-tracking variant that reconstructs the actual path, and an early-exit form for single-target queries.

JavaScript
algorithms
dijkstra
code-template
heap

1.1k

17

Hard
Code Snippet
Premium

Topological Sort (Kahn's Algorithm)

Topological sort orders the nodes of a DAG so that every edge points from earlier to later. It is the algorithm behind build-system dependency resolution, course-prerequisite scheduling, and pipelined computation. This snippet covers Kahn's BFS-based algorithm with indegree tracking, a DFS-based variant that produces the same order via post-order, and a cycle-detection variant that returns null when the graph is not acyclic.

JavaScript
algorithms
topological-sort
code-template
bfs

681

7

Hard
Code Snippet

Python List Comprehension Cheat Sheet

List comprehensions are Python's most distinctive feature: they pack filter, map, and flatten into a single expression. This cheat sheet covers the basic map-and-filter form, the nested form for cartesian products and matrix flattening, and the conditional-expression form that branches inside the output. Each pattern shows up many times per Python file in real codebases.

Python
py-list-comprehensions
py-comprehensions
code-template
cheat-sheet

451

11

Easy
Code Snippet

Python Dict Comprehension Cheat Sheet

Dict comprehensions build mappings without explicit loops, the same way list comprehensions build lists. They are the right tool for inverting a dict, projecting a list of tuples into a key-value map, and filtering an existing dict by predicate. This snippet covers the basic build form, the invert and merge patterns, and the filtering form for trimming an existing dict.

Python
py-comprehensions
py-list-comprehensions
code-template
cheat-sheet

1.1k

15

Easy
Code Snippet

Python Set Comprehension Patterns

Set comprehensions are the underused sibling of list and dict comprehensions. They build deduplicated collections in one line and excel at unique-by-key extraction, set algebra, and quick membership filters. This snippet covers the basic uniqueness pattern, the unique-by-projection form for objects, and set algebra (intersection, difference) expressed as comprehensions.

Python
py-comprehensions
py-list-comprehensions
code-template
cheat-sheet

1k

20

Easy
Code Snippet

Walrus Operator Patterns

The walrus operator `:=` (Python 3.8+) lets you assign and use a value in the same expression. It is the right tool for caching expensive expressions inside comprehensions, reading until a sentinel, and tightening the common 'compute, then check' pattern. This snippet covers the loop-with-sentinel use, the comprehension-cache use, and the regex-match conditional that is the most-cited textbook example.

Python
py-walrus-operator
code-template
cheat-sheet
py-standard-library

605

11

Medium
Code Snippet

Counter for Frequency Counting

`collections.Counter` is the dict-of-counts that every other 'count occurrences' implementation tries to be. It supports increment-by-add, most-common-K, and arithmetic between counters. This snippet covers the basic frequency count, the most-common-K shortcut, and the multiset arithmetic that makes Counter the right choice for inventory math and difference reports.

Python
py-collections
py-standard-library
code-template
hash-table

1.1k

25

Easy
Code Snippet

defaultdict for Implicit Init

`collections.defaultdict` removes the boilerplate of checking-then-initialising before every increment or append. It supplies a default value when a missing key is read, and that default lives in the dict from then on. This snippet covers the bucket-by-key pattern with `defaultdict(list)`, the count pattern with `defaultdict(int)`, and a nested `defaultdict` for two-level groupings.

Python
py-collections
py-standard-library
code-template
hash-table

348

2

Easy
Code Snippet

deque for O(1) Append and Pop on Both Ends

A `collections.deque` (double-ended queue) supports O(1) `append`, `appendleft`, `pop`, and `popleft`, while a Python `list` is O(n) for left-side operations. This snippet covers the deque-as-queue pattern that powers BFS, the deque-as-rolling-buffer pattern with `maxlen`, and the rotate trick for cyclic processing.

Python
py-collections
py-standard-library
code-template
queue

920

9

Easy
Code Snippet

namedtuple for Lightweight Records

`collections.namedtuple` produces a tuple subclass with named fields, giving you the immutability and packing of a tuple plus the readability of a dataclass. It is the right choice for tiny return-record types that should be cheap and hashable. This snippet covers the basic factory, the typed `NamedTuple` form from `typing`, and the `_replace` and `_asdict` helpers for record-style updates and JSON conversion.

Python
py-collections
py-standard-library
code-template
py-dataclasses

1k

11

Easy
Code Snippet

OrderedDict Quirks Worth Knowing

Regular dicts have preserved insertion order since Python 3.7, so most modern code never reaches for `OrderedDict`. But OrderedDict still has a niche: it ships with `move_to_end` and `popitem(last=False)` methods that plain dicts do not, and its equality semantics differ from dict equality. This snippet covers the move-to-end LRU primitive, the order-sensitive equality, and when you should still pick OrderedDict in 2025.

Python
py-collections
py-standard-library
code-template
lru-cache

577

5

Medium
Code Snippet

ChainMap for Layered Configs

`collections.ChainMap` lets you stack multiple dicts and treat them as a single read-through view, with later dicts shadowing earlier ones. It is the right primitive for layered configs (defaults, environment, user overrides), nested scopes, and anywhere you would otherwise merge dicts repeatedly. This snippet covers the basic stacking, lookup-with-fallback semantics, and how new keys land in the first map by default.

Python
py-collections
py-standard-library
code-template
cheat-sheet

451

10

Medium
Code Snippet

heapq Min-Heap Recipes

Python's `heapq` module turns any list into a binary min-heap in place, supporting O(log n) push and pop. It is the priority-queue primitive that powers Dijkstra, Top-K, and merging sorted streams. This snippet covers the basic push and pop, the Top-K largest pattern using `nsmallest` and `nlargest`, and the merge of multiple sorted iterables in O(N log K).

Python
py-standard-library
heap
code-template
algorithms

586

17

Medium
Code Snippet

bisect for Sorted-List Insertion

The `bisect` module is Python's binary-search-on-a-list primitive: `bisect_left` and `bisect_right` find the insertion index for a value in a sorted list in O(log n). This snippet covers the basic insertion-point query, the `insort` shortcut for keeping a list sorted as you build it, and the count-occurrences and rank-percentile recipes that fall out for free.

Python
py-standard-library
binary-search
code-template
algorithms

189

2

Medium
Code Snippet

Read and Write JSON Files Idiomatically

Reading and writing JSON in Python is two lines once you know the right defaults. The right defaults are `with open(... encoding='utf-8')`, `json.load` / `json.dump` (not `loads` / `dumps`), and `indent=2, ensure_ascii=False` for human-readable files. This entry covers the round trip, atomic write, and the common pitfalls (bytes vs text mode, default ASCII escaping).

Python
file-io
py-standard-library
code-template

772

10

Medium
Code Snippet

Python Binary Search Template

Binary search runs in O(log n) over any sorted array, but the off-by-one variations bite everyone. This entry ships three runnable templates: the equality search, the lower-bound (`bisect_left`) variant, and the upper-bound (`bisect_right`) variant. Each one handles every edge case the test list throws at it.

Python
binary-search
algorithms
code-template
binary-search-templates

1k

33

Easy
Code Snippet

Python Two-Pointer Template

The two-pointer pattern walks two indices through a sorted array, moving them inward (or together) based on a comparison. It turns many naive O(n^2) problems into O(n) sweeps. This entry covers the inward-sweep template (two-sum sorted), the same-direction template (remove duplicates in place), and a 3-sum builder that uses two pointers as the inner loop.

Python
two-pointers
algorithms
code-template
py-standard-library

930

4

Easy
Code Snippet

Python Sliding Window Template

The sliding-window pattern walks two indices forward through a sequence, maintaining an aggregate (sum, count, set, dict) of the current window. It turns 'best subarray of length K' and 'longest subarray with property P' problems into single O(n) sweeps. This entry covers the fixed-size variant, the variable-size shrink-when-invalid variant, and the longest-substring-without-repeats classic.

Python
sliding-window
algorithms
code-template
py-standard-library

1.1k

5

Easy
Code Snippet

Python BFS Template

Breadth-first search visits nodes in order of distance from the start, which makes it the right tool for shortest-path-by-edge-count, level-order traversal, and 'fewest steps' search problems. Python's `collections.deque` gives you O(1) `popleft`, which is the difference between BFS and an O(n^2) accident. This entry covers the standard template, distance tracking, and a level-by-level variant.

Python
bfs
graphs
algorithms
code-template

343

8

Medium
Code Snippet

Python DFS Templates (Recursive + Iterative)

DFS visits a graph by going as deep as possible before backtracking. Python lets you write it recursively (concise, but bounded by `sys.getrecursionlimit()`) or iteratively with an explicit stack (uglier, but safe for deep graphs). This entry ships both templates and a third variant that detects cycles in a directed graph using gray / black coloring.

Python
dfs
graphs
code-template
recursion

775

25

Medium

Community

31 items
Code Snippet

ANSI Colored Logger in 50 Lines

chalk is great. chalk plus chalk-template plus log-symbols plus signal-exit is heavy. Here is the dependency-free ANSI logger I drop into every Node script when I want one-line wins without 14 transitive packages.

JavaScript
logging
input-output
code-template

1.1k

34

4.2 (11)

May 12, 2026

by @carlosherrera

Code Snippet

Pandas Melt-Then-Pivot: The Shape I Always Need

I keep reaching for melt-then-pivot to reshape wide tables for charting. Here is the pandas-style transform written in pure stdlib Python so it runs anywhere, plus the multi-key pivot variant.

Python
py-collections
data-pipeline
code-template

705

21

4.3 (14)

May 10, 2026

by @carlosherrera

Code Snippet

Streaming Aggregations With a Single Pass (JS)

Welford's online algorithm for mean and variance, plus a 30-line streaming p99 estimator. The version I use when the data does not fit in memory or arrives over WebSocket.

JavaScript
stream-processing
performance
code-template

851

26

4.2 (12)

May 9, 2026

by @ryancastillo

Code Snippet

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.

TypeScript
testing
http
code-template
utility

1k

26

4.4 (9)

May 8, 2026

by @ezb1981

Code Snippet

Freeze Time and Fast-Forward in Jest

The clock-control playbook I keep on a sticky note: freeze `Date.now`, advance pending timers without sleeping, and write tests for debounce/throttle helpers that actually finish in milliseconds.

JavaScript
testing
unit-testing
code-template

193

2

4.6 (8)

May 2, 2026

by @rohanbakr

Code Snippet

An argv Parser Without yargs or commander

Eighty percent of the time I just need --flag and --opt=value parsing for a one-off script. Adding yargs feels heavy. This is the 30-line zero-dependency parser I copy into every Node script.

JavaScript
input-output
code-template
functional-programming

460

8

4.4 (12)

May 1, 2026

by @nehanasser

Code Snippet

The Union-Find With Rank I Copy Into Every Contest

After timing out on a Codeforces 'connected components' problem twice, I memorized this 25-line union-find with path compression and union-by-rank. The find() is iterative (no recursion to blow the stack) and component_count is O(1).

JavaScript
union-find
path-compression
graphs
code-template

895

22

4.3 (11)

Apr 30, 2026

by @emmadiallo

Code Snippet

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.

Python
testing
unit-testing
code-template
utility

687

2

4.3 (14)

Apr 30, 2026

by @yunatorres

Code Snippet

The Trie I Built for Search-Bar Autocomplete

We had 80k product names and a 600ms p95 on prefix lookup. A trie keyed by lowercased characters with per-node frequency counts cut it to 4ms and let us rank suggestions by popularity in the same pass.

JavaScript
trie
autocomplete
search
code-template

918

29

Apr 25, 2026

by @ethanhadid

Code Snippet

Prompt for y/N Without readline Cruft

Every CLI script needs a confirm() one day. The full Inquirer ceremony is overkill. Here is the small wrapper I copy into deploy scripts when I need 'are you sure? [y/N]' that defaults to no.

JavaScript
input-output
code-template

1k

33

Apr 25, 2026

by @petrawilson

Code Snippet

Dedupe by Key With Last-Write-Wins (JS)

dedupeBy(rows, 'id') is the function I copy into every ETL script. Last-write-wins is the right policy 90% of the time; this version also exposes a configurable resolver for the other 10%.

JavaScript
hash-map
code-template
data-pipeline

561

5

4.7 (8)

Apr 15, 2026

by @camilarao

Code Snippet

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.

JavaScript
http
error-handling
code-template
utility

1k

32

4.2 (9)

Apr 13, 2026

by @leoeriksson

Code Snippet

A stdout Progress Bar Without a Library (Python)

tqdm is wonderful but adds 30k of dependencies for a 30-line job. Here is the pure-stdlib progress bar I drop into ETL scripts when I just want to know how far through the file I am.

Python
input-output
code-template
py-generators

359

8

Mar 31, 2026

by @rajtanaka

Code Snippet

A Server-Sent Events Consumer That Reconnects

The Node-friendly SSE client I write whenever the browser `EventSource` is the wrong tool. Parses the line protocol by hand, resumes from `Last-Event-ID`, and applies bounded backoff between retries.

JavaScript
sse
real-time
http
code-template

813

7

4.3 (12)

Mar 29, 2026

by @jordandubois

Code Snippet

The Five Custom TS Utility Types I Add to Every Project

TypeScript ships great utility types but the five I miss in every fresh project are these: NonEmptyArray, Branded, Awaited inverse (Promisify), DeepReadonly, and ExactKeys. Each is one or two lines that has saved me from a bug.

TypeScript
type-system
generics
code-template

834

14

4.3 (14)

Mar 21, 2026

by @tylerperry

Code Snippet

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.

Python
debugging
networking
code-template
utility

382

3

4.4 (9)

Mar 17, 2026

by @elisehuang

Code Snippet

A Circuit Breaker State Machine in JavaScript

The 80-line breaker I drop in front of every flaky upstream. Three explicit states, a half-open probe, and a clock you can swap out for tests. No `opossum`, no `cockatiel`, no Redis.

JavaScript
circuit-breaker
resilience
fault-tolerance
code-template

407

3

4.5 (11)

Mar 9, 2026

by @vikramross

Code Snippet

A Request/Response Logger That Does Not Leak Secrets

The redact-by-key logger I add to every Node service before it touches production logs. Catches headers, JWTs, card numbers, and Stripe keys without paying for a SIEM scrubber.

TypeScript
logging
security
error-handling
code-template

434

14

4.4 (15)

Mar 6, 2026

by @nadiaali

Code Snippet

useFormField Hook With Field-Level Validation

A field-scoped form hook for the cases where react-hook-form is overkill. Tracks value, touched, blur, and an async validator with a single race-safe in-flight token.

JavaScript
react
hooks
code-template
error-handling

729

13

4.5 (10)

Feb 23, 2026

by @leoeriksson

Code Snippet

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.

Python
debugging
py-decorators
utility
code-template

994

4

4.5 (13)

Feb 14, 2026

by @owentoure

Code Snippet

Quick Sort in Three Lines, and Why It's Wrong

Every interview blog shows the cute three-line quicksort. It's a teaching aid that looks elegant and ships bugs: O(n log n) extra memory, quadratic on sorted input, and unstable. Here is the cute version, the in-place version we should actually write, and the version with a randomized pivot.

Python
quick-sort
sorting
code-template
algorithms

479

4

Feb 13, 2026

by @nathanmurphy

Code Snippet

groupby Then Aggregate With defaultdict (Python)

Pure stdlib group-then-aggregate: defaultdict(list) for the grouping pass, then a tiny per-group reducer. The version I reach for before importing pandas, plus the multi-stat variant.

Python
py-collections
py-itertools
code-template

280

6

4.4 (8)

Feb 8, 2026

by @elenamuller

Code Snippet

A Prompt Template With Safe Interpolation

After a customer email leaked into a system prompt and changed the model's persona, I built a 30-line template that quotes user input, fences code, and refuses unknown placeholders. Use it before every LLM call.

Python
openai
security
code-template
error-handling

1k

10

4.4 (15)

Feb 4, 2026

by @elisehuang

Code Snippet

Paste-Image-From-Clipboard Handler

When a user hits Cmd-V with a screenshot in their clipboard, we want to upload it as if they had drag-dropped. This is the 30-line paste handler I keep, including the Safari-only `clipboardData.items` traversal and a graceful HEIC fallback.

JavaScript
js-dom
frontend
code-template

956

28

4.2 (10)

Jan 14, 2026

by @rajreeves

Code Snippet

Binary Search on the Answer Space

I had to bin-pack 5M jobs across N machines under a wall-time budget; sort-and-greedy timed out. The fix was binary searching the makespan: a `feasible(m)` predicate plus the standard lo/hi loop turns an NP-hard scheduler into O(N log range).

JavaScript
binary-search
problem-solving
code-template

647

21

4.4 (13)

Jan 12, 2026

by @rohaneriksson

Code Snippet

The 12-Column Grid I Keep, With Named Areas and Container Queries

I rewrote our marketing site grid three times before settling on this: a 12-column CSS Grid with named areas for the hero shape, container queries for the breakpoints, and custom properties for the gutter so designers can change one value.

CSS
css-grid
css-variables
code-template
frontend

1.1k

15

4.4 (13)

Jan 11, 2026

by @lucasmoreau

Code Snippet

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.

JavaScript
react
hooks
code-template
utility

851

20

4.4 (8)

Dec 24, 2025

by @petrawilson

Code Snippet

Debounce With Leading + Trailing Edges and a cancel() Method

The trailing-only debounce in every tutorial works for search inputs and breaks on click handlers. Here is the lodash-style version with leading edge, cancel(), and flush(), in 30 lines.

JavaScript
throttling
performance
code-template

915

13

4.4 (8)

Dec 18, 2025

by @hiroshiward

Code Snippet

CSV With Quoted Commas: The 30-Line Parser

split(',') gets you fired on the first row that contains a comma inside quotes. Here is a state-machine CSV parser in 30 lines that handles quoted commas, escaped quotes, and CRLF endings.

JavaScript
serialization
code-template
input-output

296

8

4.3 (11)

Dec 14, 2025

by @gracechoi

Code Snippet

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.

JavaScript
testing
unit-testing
utility
code-template

368

12

4.2 (11)

Dec 14, 2025

by @marcusreddy

Code Snippet

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.

JavaScript
js-dom
code-template
frontend
utility

323

1

4.4 (13)

Dec 6, 2025

by @isabellarashid