Take While and Drop While Array Helpers
Implement takeWhile and dropWhile helpers that stop testing after the first failure and never mutate the source array.
Page 10 of 14
Implement takeWhile and dropWhile helpers that stop testing after the first failure and never mutate the source array.
Create readable fixtures with layered overrides, per-item variation and reset support, keeping tests free of duplicated object literals.
Limit function execution frequency with configurable leading and trailing edges, plus cancel and flush controls for cleanup.
Store weighted words in a case-insensitive trie and return autocomplete suggestions ranked by weight and prefix match.
Shorten UI text by grapheme clusters so emoji and combining marks stay intact, with an ellipsis budget included.
Find two array indices whose values sum to a target in one pass using a hash map, with validation for non-numeric input.
Remove duplicate objects from an array using a key function or property name, preserving original order and first occurrences.
Normalize HTTP URLs by removing default ports and fragments, sorting query pairs and dropping tracking parameters for stable cache keys.
Generate time-ordered UUIDv7 identifiers with a 48-bit millisecond prefix and a 12-bit counter that keeps values increasing.
Compute a weighted mean from value and weight arrays, rejecting length mismatches, non-finite numbers and invalid total weight.
Trim, collapse and optionally preserve line breaks while removing zero-width characters that break search and comparison.
Compute fixed monthly payments and a full amortization table with Decimal rounding, then total the interest paid.
Fan out jobs to a bounded asyncio queue, run a fixed worker pool, and shut down cleanly with sentinel values and task_done.
Relax all edges to compute shortest paths from one source, rebuild the route, and report a reachable negative cycle.
Find lower and upper insertion bounds in sorted sequences with optional key functions, plus exact search and duplicate counting.
Size a Bloom filter from an expected item count and false-positive rate, then add and test members using double hashing.
Estimate a confidence interval for any statistic by resampling with replacement, using a seeded random generator for repeatable runs.
Find a strict majority in one pass with constant memory, verify the candidate, and collect every value above one third.
Distribute keys across nodes with a SHA-256 consistent hash ring, virtual replicas, node add and remove, and minimal key movement.
Extract a safe basename from Content-Disposition headers, honoring RFC 5987 encoding and rejecting traversal segments.
Generate repeatable fake users from a seeded random source, with per-call overrides and stable identifiers for snapshots.
Track a smoothed moving average with a period-derived smoothing factor, plus a windowed simple average for comparison.
Compute file checksums in fixed-size chunks, support alternate hashlib algorithms, and verify expected digests in constant time.
Convert seconds into compact day, hour, minute, and second strings and parse those strings back with strict validation.
Abstract time behind a Clock protocol, provide a fake clock that can advance instantly, and drive a TTL cache without sleeping.
Normalize half-open intervals, merge overlaps or adjacent ranges, and reject invalid bounds with clear validation errors.
Apply RFC 6902 add, remove, replace, move, copy, and test operations through JSON Pointers while leaving the input document unchanged.
Compute edit distance in O(n*m) time and O(min(n,m)) space, calculate similarity, and suggest the closest matching candidate.
Memoize async loader results with a per-key TTL and lock so concurrent misses trigger one upstream call instead of a herd.
Cancel running asyncio workers, catch CancelledError for cleanup, and report how many items were processed before shutdown.
Limit concurrent asyncio tasks with a semaphore, keep input order in the results, and report per-task failures without cancelling the batch.
Run coroutines in an asyncio.TaskGroup so the first failure cancels siblings, then inspect the raised ExceptionGroup.
Encode integers with Crockford Base32 and decode human-typed values that contain hyphens or confusable letters like O and I.
Encode payloads as Base58 with a double SHA-256 checksum, preserve leading zero bytes, and reject corrupted input on decode.
Group any iterable into fixed-size lists lazily, preserve the final partial batch, and stop cleanly when the source is exhausted.
Wrap state changes in a context manager that commits on success, restores a snapshot on any exception, and re-raises the error.
Parse five-field cron expressions and compute the next run times, including weekday and month boundaries.
Detect a CSV delimiter and quote style from a sample, then parse rows into dictionaries without hard-coding comma assumptions.
Stream CSV rows with the csv module, validate required headers, convert typed fields, and route rejected rows to a separate file.
Enforce types and ranges on dataclass fields at construction time, normalize values, and raise one error listing every invalid field.
Split a Decimal amount across integer weights while keeping cent-level totals exact, distributing leftover cents deterministically.
Merge nested configuration mappings layer by layer, replacing scalars and lists while keeping the default tree untouched.
Race several async replicas, return the first successful result, cancel the losing tasks, and report a clear failure.
Compute shortest distances between every pair of nodes and reconstruct routes with a next-hop matrix in O(n^3) time.
Select the k largest or smallest scores with heapq, keep memory bounded at k entries, and sort ties by name for stable output.
Validate webhook payload signatures with HMAC-SHA256, constant-time comparison, and a timestamp window that blocks replay attacks.
Flag usernames that mix Latin with Cyrillic or Greek letters used as lookalikes, and explain each suspicious character.
Resume an interrupted HTTP download with a Range request, appending only missing bytes and restarting when the server ignores it.
Normalize and validate IBAN values with length, character, and mod-97 checksum rules before persisting account data.
Normalize hyphens and spaces, then verify ISBN-10 and ISBN-13 check digits with the official weighted modulo rules.
Convert nested JSON objects to dotted key paths and reconstruct them, rejecting conflicting paths instead of silently overwriting.
Iterate JSON Lines files lazily, skip blank lines, report malformed records with line numbers, and cap record size to avoid memory spikes.
Reduce floating-point drift with Kahan and Neumaier compensated summation, and see where plain left-to-right addition loses a value.
Fit a straight line through paired x and y values using least squares, then compute the coefficient of determination and predict new points.
Parse RFC 8288 Link headers into named relations while respecting commas inside quoted titles and target URLs.
Configure Python logging with a rotating file handler that caps file size, keeps numbered backups, and flushes each record.
Build a thread-safe LRU cache on OrderedDict with capacity eviction, hit and miss counters, and a memoize decorator for pure functions.
Run operator-supplied regular expressions with the regex module timeout, an input length cap, and explicit failure handling.
Resolve user-supplied relative paths under a fixed root, reject absolute or traversal inputs, and verify the final path stays inside.
Extract gzipped tar archives after rejecting absolute paths, parent traversal, and link members that escape the destination.
Parse and compare semantic version strings with prerelease precedence, then sort a mixed release list correctly.
Apply a batch of stock updates inside one SQLite transaction with validation, ON CONFLICT upserts, and rollback on any bad row.
Build a durable SQLite job queue that claims work with a time-limited lease, retries abandoned jobs, and deletes finished rows.
Parse text/event-stream frames into structured events and wrap the HTTP read loop with bounded reconnect attempts and backoff.
Emit JSON log lines with a custom formatter, attach request context through ContextVar, redact secret fields, and keep UTC timestamps.
Rank the most distinctive keywords in a small document set with term frequency, inverse document frequency, and stop-word filtering.
Implement a monotonic-clock token bucket that allows bursts, refills at a fixed rate, and returns the wait time when a request is denied.
Parse TOML into frozen dataclasses, validate nested service and database tables, and report missing or mistyped keys with clear errors.
Order build targets from a prerequisite graph with Kahn's algorithm and fail loudly when a dependency cycle prevents a complete order.
Insert weighted words into a trie, autocomplete by prefix, rank suggestions by weight, and reject empty or non-string input.
Turn Unicode headings into stable ASCII URL slugs with transliteration, separator collapsing, and length limits.
Track connected components with union by rank and path compression, then answer connectivity queries in near-constant time.
Encode non-negative integers as compact LEB128 bytes and decode them sequentially, with ZigZag helpers for signed values.
Track count, mean, and sample standard deviation in one pass with Welford's algorithm, avoiding catastrophic cancellation.
Read a large XML document without loading it whole, yield one record at a time, and clear processed elements to free memory.
Parse repeated query parameters into a multimap, rebuild a stable query string, and read typed single-value flags safely.
Keep the newest N items in a fixed-size circular buffer, return the evicted value on overflow, and read the latest slice.
Turn untrusted filenames into safe basenames by stripping paths, blocking reserved names, normalizing Unicode, and limiting length.
Split plain text into sentences while keeping common abbreviations, decimals, and closing quotes attached to the right sentence.
Run safe parameterized SQLite queries with bound values, allowlisted sort columns, dynamic IN clauses, and repository error handling.
Encode and decode length-prefixed binary packets with a magic header, version checks, payload limits, and truncation errors.
Walk a directory without following links that escape the root, recording skipped entries and enforcing a depth limit.
Map a function over items with a bounded thread pool, preserve input order, and cancel pending work when the overall deadline expires.
Normalize scheme, host, port, dot segments, and query order while dropping tracking parameters, producing a stable cache key.
Reload configuration atomically by swapping an Arc while readers keep lock-free snapshots, with no downtime or partial state.
Share a child cancellation token with each worker and cancel the whole batch when the execution budget runs out.
Compare secrets without early exit so timing does not leak the matching prefix, and keep the result observable with black_box.
Schedule named tasks with run-at timestamps in a binary heap, pop everything that is due, and inspect the next deadline.
Parse and build big-endian length-prefixed frames with a version byte, flags, checksum, and explicit truncation errors.
Match strings against star and question-mark patterns with backtracking that avoids exponential blowup on repeated stars.
Count differing bits between equal-length byte slices, report bit similarity, and reject inputs of unequal length.
Convert bytes to lowercase hex and back, accepting an optional prefix and embedded whitespace while rejecting invalid digits.
Parse INI sections and key-value pairs into a sorted map, trimming quotes and rejecting malformed headers or empty keys.
Identify PNG, JPEG, GIF, PDF, ZIP, and gzip files from their leading bytes, then check whether the extension agrees.
Normalize an untrusted relative path component by component and reject anything that would climb above the allowed root.
Serve typed JSON from Axum 0.8 with path and query extractors, explicit 400 and 404 errors, and shared map state behind an Arc.
Keep the largest K values from a stream in a bounded min-heap using Reverse, then return them sorted from highest to lowest.
Coordinate producers and consumers with a bounded VecDeque, Mutex, and two condition variables for blocking push and pop.
Split identifiers on separators and case boundaries, then rebuild them as snake_case or camelCase without external crates.
Track failures with closed, open, and half-open states so a failing dependency is rejected fast until a cooldown trial succeeds.