Commander Git-Style Subcommand CLI
Build a git-style CLI with Commander using nested subcommands, variadic arguments, option conflict rules, and typed hook-driven configuration.
Page 2 of 3
Build a git-style CLI with Commander using nested subcommands, variadic arguments, option conflict rules, and typed hook-driven configuration.
Compose a list of functions so each wraps the next, matching the middleware style used by many web frameworks.
Split a CSV line into fields while respecting quoted values that contain commas or escaped quotes, a step that naive splitting gets wrong.
Parse CSV as a stream with csv-parse, validate each row against a schema, and pipe valid records onward while collecting row-level errors.
Curry a function so partial application returns a new function until every argument is supplied, enabling reusable configured variants.
Convert timestamps between timezones with Dayjs and its UTC plugin, keeping wall-clock semantics intact and formatting per-locale output.
Debounce wraps a callback so it runs only after activity stops for a set wait, collapsing bursts of calls into a single trailing invocation.
Remove duplicate records that share a key, keeping the first or last occurrence so the result is deterministic and easy to reason about.
Clone nested objects and arrays without sharing references, using the structured clone algorithm so dates, maps, and cycles are handled correctly.
Merge nested config objects where later sources override earlier scalars but nested objects are combined recursively, a common layering need.
Handle Docker stop signals in Node so in-flight requests drain, background jobs checkpoint, and the process exits within the grace period.
Layer environment configuration from shared defaults through environment-specific files up to process environment with explicit override rules.
Escape untrusted text before inserting it into HTML so angle brackets and quotes cannot break out of the surrounding context.
Build a small publish and subscribe emitter that registers listeners per event name and supports one-shot subscribers and clean removal.
Run child processes with execa to get parsed stdout and stderr, shell-free argument arrays, and non-zero exit codes surfaced as typed errors.
Route async failures into Express error middleware with a wrapper, classify status codes, and mask internal details before responding.
Accept streaming multipart uploads in Fastify with per-file size limits, MIME allowlists, and disk writes that never buffer whole files.
Wire Fastify to Pino for structured request logging with redaction, request ids, sampling, and slow-request warnings under load.
Read a fetch response body as a stream with manual reader control, honoring backpressure so a slow consumer cannot balloon memory.
Fetch JSON from an endpoint, applying a per-attempt timeout and retrying transient failures while treating client errors as final.
Subscribe to Firebase auth state, read the current ID token before each API call, and let the SDK refresh expired tokens transparently.
Flatten arrays nested to an arbitrary depth into a single level, with an optional depth limit so callers can control how far the flattening goes.
Validate a submitted form object against field rules and collect every error at once, so users see all problems instead of one at a time.
Configure the got client to retry transient failures with exponential backoff, status-code allowlists, and per-attempt timeouts for safer polling.
Fetch paginated GraphQL connections with graphql-request, following cursor edges and pageInfo detection until the full dataset is drained.
Group an array of records into a map keyed by one of their fields, a building block for reports, indexes, and bucketed aggregations.
Build interactive CLI flows with Inquirer checkbox prompts, validated input, default selections, and answer-driven branching between steps.
Harden ioredis connections with retry backoff, command timeouts, and sentinel failover so cache clients survive restarts and primary swaps.
Verify tokens against a rotating JWKS endpoint with jose, pinning allowed algorithms and caching the key set with stale fallback on outages.
Sign and verify JWTs with the jose library using an ECDSA P-256 key pair, protected headers, and explicit audience and expiry validation.
Decode the payload of a JSON Web Token and verify that its expiry and not-before claims are respected, without trusting the token's signature blindly.
Compose Koa middleware functions in explicit execution order, tracing the onion model pass-through with early termination and downstream control.
Compute the minimum number of insertions, deletions, and substitutions between two strings, the basis of fuzzy matching and spell suggestions.
Tame high-frequency DOM and scroll events with Lodash debounce and throttle, including leading and trailing edge control and cancelable handles.
Implement a least-recently-used cache that evicts the oldest entry when capacity is exceeded, reusing Map insertion order to track recency.
Combine LRU eviction with TTL expiry and stale-while-revalidate semantics so hot keys stay warm, expired entries serve stale, and refreshes dedupe.
Model calendar-aware time spans with Luxon Interval and Duration, splitting ranges into months, comparing overlaps, and humanizing output.
Cache a function's result by argument key with an expiry, so expensive pure calls are reused briefly and stale values eventually recompute.
Paginate large MongoDB collections with stable cursor queries on indexed compound sort keys, avoiding skipped documents on offset paging.
Group multi-document writes into an atomic MongoDB transaction with a session, abort on validation failure, and retry on transient errors.
Generate compact, URL-safe identifiers with nanoid, sized from collision probability math instead of guesswork, with a custom alphabet option.
Hash passwords with the built-in scrypt using random per-user salts, explicit cost parameters, and timing-safe comparison on verification.
Chain readable, transform, and writable streams with pipeline to process large files in constant memory while propagating backpressure and errors.
Offload CPU-bound work to a pool of worker threads with Piscina-style sizing, transferable buffers, and graceful pool shutdown.
Compare two flat objects field by field and report added, removed, and changed keys, the core of audit logging and change detection.
Cap parallel task execution with p-limit so large batches of promises run at a fixed concurrency instead of exhausting memory or API quotas.
Slice an array into a page and return metadata such as total pages and whether more results follow, the shape most list endpoints expose.
Query PostgreSQL through a pg pool with always-parameterized statements, statement timeouts, idle client recycling, and pool sizing guidance.
Prevent secrets from leaking into logs by configuring Pino redaction paths, nested wildcard censoring, and strict serializer boundaries.
Instrument a service with prom-client counters for totals, histograms for latency buckets, and a default metrics endpoint for scraping.
Run an array of async tasks with a maximum concurrency, so a large batch does not open all connections at once and overwhelm a downstream service.
Find the kth largest element in average linear time with quickselect, avoiding the cost of fully sorting when only one rank is needed.
Build point-free data transformation pipelines with Ramda compose, lens-based updates, and curried predicates that stay testable end to end.
Enforce a distributed rate limit with rate-limiter-flexible backed by Redis points, insurance fallback, and per-key consumption tracking.
Render React server-side to a node stream with Suspense boundaries so fast content flushes first and slow data streams in without blocking.
Build a Redis-backed caching layer with TTL eviction, LRU maxmemory policy, cache-aside reads, and explicit invalidation on writes.
Wrap flaky operations with the retry package using predicate-based retries, exponential factors, randomization, and per-operation abort signals.
Retry a flaky async operation a bounded number of times, doubling the delay between attempts, adding jitter, and only retrying errors that are safe to repeat.
Enforce least-privilege access with composable role middleware that verifies tokens, resolves roles, and gates routes without inline checks.
Limit how many callers may hold a resource at once with a counted semaphore that queues waiters and releases permits fairly.
Track request timestamps in a sliding window to count how many calls happened in the last interval, rejecting requests that exceed the allowed rate.
Build dynamic IN clauses with generated placeholders instead of string interpolation, keeping every user value bound as a statement parameter.
Speed up static site builds by hashing content inputs per page, reusing unchanged build cache entries, and invalidating only affected pages.
Process a text stream line by line with a transform, keeping partial chunks buffered so splitting on newlines does not corrupt records.
Consume newline-delimited JSON streams line by line using async iteration over the response body, parsing each record with error isolation.
Query a Supabase table with typed client filters, range pagination, upsert conflicts, and realtime subscription cleanup in one flow.
Use Superagent to GET and POST with automatic parsing, retries, timeout control, and typed response body access for JSON and form payloads.
Throttle limits how often a function runs by allowing at most one call per interval, useful for scroll and resize handlers that fire continuously.
Order a dependency graph so every node appears after its prerequisites, reporting a cycle when no valid order exists.
Create an undici Agent with per-origin connection limits and pipelining depth, then dispatch pooled HTTP requests with explicit abort timeouts.
Write Vitest unit tests for an Express app with Supertest, covering success paths, validation errors, and HTTP status assertions per case.
Keep a WebSocket client alive through disconnects with exponential backoff reconnect, jitter, heartbeat pings, and a bounded retry budget.
Rotate application logs by day and size with winston-daily-rotate-file, keeping bounded history, zipped archives, and separate error streams.
Parse and validate process.env at boot with a Zod schema so missing or malformed configuration fails fast before any request is served.
Parse Accept headers with q-values and wildcards, then pick the best supported media type while honoring q=0 exclusions and server order.
Compute exact years, months and days between a birth date and a reference date using UTC date-only arithmetic.
Split arrays or any iterable into fixed-size chunks with strict size validation, ordered output and a lazy generator variant.
Combine parallel arrays into tuples and split a collection by predicate, with a zipLongest variant that pads short inputs.
Serialize critical sections with an async mutex that queues waiters in FIFO order, supports acquisition timeouts and safe double release.
Check whether parentheses, square brackets and braces are balanced and correctly nested with a single-pass stack algorithm.
Encode UTF-8 text with the RFC 4648 Base32 alphabet, add correct padding, and decode back while rejecting invalid characters.
Encode strings or bytes to unpadded base64url and decode back with strict alphabet, length and fatal UTF-8 validation.
Find the first and last insertion points for a value in a sorted array with a custom comparator, then count duplicates in logarithmic time.
Represent up to 30 permissions as one 32-bit mask with helpers to build, test, add, remove, toggle and list enabled flags.
Find a strict majority element in linear time and constant space, plus a generalized Misra-Gries pass for multiple frequent values.
Append a stable version or content-hash query parameter to asset URLs without losing existing params or fragments.
Shift ASCII letters by any integer offset with alphabet wrapping, and expose ROT13 as a fixed thirteen-position special case.
Convert identifiers between camelCase, snake_case and kebab-case with word-boundary splitting, input validation and predictable output.
A cooperative cancellation primitive with reasons, unsubscribe callbacks, throwIfCancelled and linked token sources that cascade cancellation.
Parse MM/YY card expiry values, compare them against an injectable clock and report whether the card is valid through month end.
Format large counts as 1.2K or 3.4M with Intl.NumberFormat compact notation and configurable locale and precision.
Map over an array with a fixed concurrency limit, preserve result order, propagate the first error, and honor an AbortSignal.
Compare secrets without early exit by XOR-ing UTF-8 bytes, reducing timing leaks in token and signature checks.
Parse attachment and inline headers, including RFC 5987 filename*, while stripping directory components from untrusted names.
Parse a Cookie request header into a null-prototype object, handling quoted values, duplicates and RFC 6265 rules.
Serialize browser cookies with Max-Age, Expires, Path, Domain, Secure, HttpOnly and SameSite, plus a tolerant Cookie header parser.
Parse one CSV row with a configurable delimiter, quoted fields, doubled quotes and strict errors for malformed input.
Incrementally parse CSV chunks with quoted fields, escaped quotes, embedded newlines, and CRLF endings using a dependency-free state machine.
Transform multi-argument functions into curried variants that support placeholders and partial application.
Recursively freeze arrays and objects while tolerating cycles, accessors and typed arrays that cannot be frozen with elements.