Group Slice Rows Into Map By Key
Collect slice rows into map[string][]T buckets keyed by a field, then sort the keys so grouped output stays stable across runs.
Page 34 of 50
Collect slice rows into map[string][]T buckets keyed by a field, then sort the keys so grouped output stays stable across runs.
Compare map key sets with intersect and difference helpers, then sort results since map iteration order is randomized on every run.
Use comparable structs and fixed-size arrays as map keys so composite coordinates collapse to one entry, while slice keys are a compile-time error.
Merge several channels and set drained ones to nil so their select cases stop firing, letting the fan-in loop finish instead of spinning on zero values.
Test membership and equality with slices.Contains, ContainsFunc, IndexFunc, and EqualFunc so lookups and comparisons stay declarative.
Locate the first qualifying position with sort.SearchInts and the predicate-based sort.Search, handling the all-true and all-false boundaries yourself.
Load named zones with LoadLocation, pin offset-less wall clocks with ParseInLocation, and convert the same instant across UTC and other zones.
Show an unbuffered channel blocking the sender until the receiver is ready, while a buffered channel absorbs sends up to capacity without anyone waiting.
Parse a URL into components, mutate the query with url.Values Add, Set, and Del, then re-encode it — with QueryEscape for free-form text values.
Range over strings knowing indexes are byte offsets, count runes instead of bytes, and cut safely with ValidString guarding mid-rune slices.
Serve both LIFO and FIFO flows from one ArrayDeque: push/pop for undo stacks, offer/poll for queues, plus first/last access on both ends.
Do money math with BigDecimal instead of double: explicit setScale with RoundingMode, and compareTo instead of equals because scale makes 2.50 differ from 2.5.
Split text into words and sentences at locale-correct boundaries with BreakIterator, so apostrophes, decimals like 2.5, and abbreviations stay one token.
Encode the same string to UTF-8, UTF-16, and ISO-8859-1 and compare byte counts: UTF-8 roundtrips faithfully while unmappable chars degrade to ?.
Decode bytes that may be truncated UTF-8 with an explicit CharsetDecoder: REPORT rejects malformed input with an exception, REPLACE substitutes U+FFFD.
Encrypt sensitive fields with AES/GCM/NoPadding: a fresh 96-bit IV per message, a 128-bit auth tag on the ciphertext, and exceptions on tampering.
Compare strings the way users expect with a locale Collator; strength levels decide whether accents and case count as a difference when sorting.
Bound slow async calls with orTimeout and completeOnTimeout so a hung supplier resolves to a fallback value instead of blocking the caller forever.
Iterate a CopyOnWriteArrayList while updates land: the iterator holds an immutable snapshot, so concurrent modification never throws mid-loop.
Schedule retries with a DelayQueue: Delayed tasks become takeable only after their delay elapses, and the earliest deadline always leaves the queue first.
Guard a batch job against duplicate runs with FileChannel.tryLock: skip when another process holds the lock, release it when the run finishes.
Compare two files byte by byte with Files.mismatch: identical content yields -1, otherwise you get the offset of the first divergent byte, no manual loops.
Choose between Collections.unmodifiableList, a live view that follows the source list, and List.copyOf, a truly immutable snapshot that rejects all writes.
Rank work by severity with a PriorityQueue comparator: poll always yields the highest priority element, no matter the insertion order.
Compose fixed-width receipts and logs with printf specifiers: types, precision, width, alignment, grouping, signs, zero padding, and radices.
Stop a long-running worker with Thread.interrupt: the loop checks isInterrupted, the blocking sleep throws InterruptedException, and the flag gets restored.
Draw bounded random numbers without a shared seed using ThreadLocalRandom.current(), so concurrent tasks never contend on one Random instance.
Pack entries into an archive with ZipOutputStream and read names plus recorded sizes back through ZipFile, closing each entry before the zip is finished.
Read data-* attributes through camelCase dataset keys and remember every value arrives as a string: numeric validation thresholds need Number coercion first.
Read upload magic numbers with DataView: getUint32 compares the PNG signature, getUint16 distinguishes JPEG, and setUint16 patches bytes in place.
preventDefault dragenter, dragover, and drop so the browser does not open the file, then read event.dataTransfer.files and accept images by MIME type.
Replace map-then-flatten chains with flatMap: each page contributes its items array in one callback and a single pass yields one flat result list.
Break out of for await and the async generator still cleans up: the consumer-side break calls return(), which runs the finally block that closes resources.
Gather text fields, repeated keys, and File values into one FormData, then inspect every entry — file names and byte sizes included — before sending.
Replace scroll listeners with IntersectionObserver: lazy-load images once near the viewport, pre-trigger with rootMargin, and disconnect on teardown.
Scrub payloads on serialize with a JSON.stringify replacer and rebuild types on parse with a reviver — tokens redacted per key, date strings revived as Date.
Persist preferences with localStorage: JSON serialize before setItem, degrade gracefully on quota or privacy errors, and repair or remove corrupt entries.
Object.freeze blocks rewrites on shared tables: in ES modules the mutation attempt throws a TypeError, so defaults survive accidental writes.
Rebuild objects from key-value pairs with Object.fromEntries: filter and remap header pairs, convert Maps to plain objects, and let later duplicate keys win.
Bucket a flat array into a plain record with Object.groupBy: callback-defined keys, undefined for missing buckets, and a null-prototype result.
When the error object itself is not needed, ES2019 allows catch without a binding: parse failures fall through without declaring an unused parameter.
Pad service names with padEnd and latency numbers with padStart to fixed widths so multi-row CLI output lines up into readable aligned columns.
Encapsulate state with # fields and # methods: the ledger cannot be read or mutated outside the class, and private keys never leak into Object.keys or JSON.
Settle a promise from outside its executor with Promise.withResolvers: hand resolve or reject to any callback, then await the promise like any other.
replaceAll rewrites every occurrence while replace stops after the first; a regex argument must carry the g flag or the call throws a TypeError.
Compare sets with the ES2024 methods union, intersection, difference, symmetricDifference, isSubsetOf, and isDisjointFrom — every call returns a new Set.
Implement Symbol.iterator as a generator method so objects work with for of, spread, and destructuring, then drive the returned iterator manually with next.
Tagged template functions intercept interpolations before they are joined: one tag escapes HTML entities, and String.raw exposes the unprocessed raw strings.
Top-level await lets module setup pause on async steps: statements after the await run only once the wait resolves, with no IIFE wrapper needed.
Read precise internal type tags with Object.prototype.toString.call, then build guards that reject wrong input shapes with the offending tag in the error.
Promises rejected without a handler never throw a stack trace: attach process.on("unhandledRejection") to record the reason and keep the process alive.
Wrap error-first Node.js callbacks with util.promisify to turn them into promise-returning functions, including custom callbacks shaped as (err, result).
Combine tallies with Counter algebra: plus merges totals, minus cancels and drops non-positive counts, and intersection and union take mins and maxes.
Group records without missing-key guards: nested defaultdict(int) totals build buckets on first touch, and a list factory collects failures in arrival order.
Use dict.keys() and dict.items() views as sets: subtract to find added and removed keys, intersect for changed pairs, and rely on views tracking live mutations.
Compare expected versus actual text with difflib: unified_diff prints review-style diffs, SequenceMatcher scores similarity, get_close_matches suggests keys.
Compose permission sets with IntFlag: bitwise OR grants, the in operator tests a single bit, and iterating a member lists the individual flags it contains.
Build aligned CLI tables with f-string format specs: left and right alignment, fixed precision, fill and center, thousands grouping, and percent rendering.
Keep ratios exact with Fraction: binary floats fail 0.1 plus 0.2 checks, fractions add and scale without drift, and results auto-reduce to lowest terms.
Sort records on several fields at once with itemgetter: dept then salary ordering, one reverse flag for the whole tuple, and attrgetter for dataclass fields.
Walk adjacent pairs with itertools.pairwise: compute deltas between consecutive prices, flag threshold jumps, and close rings by re-appending the first item.
Pass a function to re.sub so every match decides its own replacement: redact secrets with shape preserved, normalize codes, and bump versions in a single pass.
Derive deterministic identifiers with uuid5: hashing a namespace UUID with a natural key yields the same ID everywhere, so re-runs and upserts stay idempotent.
Make uneven inputs loud with zip(strict=True): what plain zip silently truncates becomes an explicit ValueError, even when a streamed side runs dry.
Fixed-size arrays carry their length in the type, so a signature can force wrong lengths out at compile time, while Vec grows and both borrow as one slice.
Recursive enums need a known size, so Box stores child nodes behind a heap pointer while match walks the owned tree to sum values and measure depth.
Wrap risky calls in std::panic::catch_unwind so a panic comes back as an Err payload and the supervisor loop keeps running instead of aborting.
When a mutation needs data from the same collection, first collect targets by shared borrow, then mutate after collect ends the borrow.
Return std::process::ExitCode from main so the process exit status reflects the outcome, with custom non-zero codes for script and CI checks.
Decode byte vectors with from_utf8_lossy so invalid bytes become U+FFFD instead of panicking, against the strict from_utf8 that keeps the bytes in Err.
Pick iter for shared borrows, iter_mut for in-place edits, and into_iter to consume the collection — each form decides what survives the loop.
chain concatenates two iterators lazily, and iter::once appends a single tail element without allocating an intermediate collection.
Pick extremes from iterators with max_by_key and min_by_key, which return the last maximum and first minimum and collapse to None on empty input.
Split parsed rows once with Iterator partition, then unwrap the valid half and unwrap_err the invalid half to keep values and reasons separate.
Answer existence questions with any and all and locate items with find and position — all four stop at the first matching element.
Thread an accumulator through scan so each output derives from prior state, and stop the whole iterator early by returning None.
Since Rust 1.88 let chains join if-let bindings with boolean checks in one condition, so earlier bindings feed later patterns without nesting.
Dispatch commands by matching string literal patterns, always ending with a catch-all arm since the compiler cannot prove str exhaustiveness.
Let structs borrow their fields instead of owning them, propagating the input lifetime through constructors so views stay zero-copy.
take_while keeps the matching prefix and skip_while drops it — both stop at the first failing item, unlike filter which scans everything.
Remove neighbors with dedup on a sorted vector, keep unsorted segments honest with plain dedup, and dedup_by_key on a chosen field.
remove keeps element order but shifts every later item, while swap_remove fills the gap with the last element in constant time and scrambles order.
Add a NOT NULL column with a constant default on PostgreSQL 11+ without rewriting the table, verified from pg_attribute atthasmissing metadata.
Watch the planner AND two single-column indexes with BitmapAnd for AND-ed predicates, and why a composite index replaces the merge with one scan.
Physically reorder a table with CLUSTER and watch pg_stats.correlation move toward 1, which makes range scans cheaper for the planner to choose.
Compare composite foreign keys with MATCH SIMPLE and MATCH FULL: only the full variant rejects rows that reference a parent with half-null keys.
CREATE STATISTICS (ndistinct) makes ANALYZE collect combined distinct counts for correlated columns, so the planner stops multiplying per-column selectivities.
Declare a foreign key DEFERRABLE INITIALLY DEFERRED so child rows can be inserted before their parents and the check happens once at COMMIT.
Give statuses a fixed lifecycle with CREATE TYPE AS ENUM: ORDER BY follows declaration order, comparisons rank labels, and ADD VALUE appends later states.
Show why LAST_VALUE returns the current row under the default frame and how ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING restores the real tail.
Read parallel plans in EXPLAIN ANALYZE: a Gather node over Parallel Seq Scan leaves, with Workers Planned and Workers Launched on large tables only.
Index infix LIKE searches with the pg_trgm extension: a GIN index on gin_trgm_ops serves %son% patterns and similarity ordering that a plain btree cannot.
Walk a reporting hierarchy whose dirty rows form a loop; the PostgreSQL 14 CYCLE clause flags rows that close a cycle and stops expanding them.
Let the database stamp each recursive CTE row with a breadth-first sequence via SEARCH BREADTH FIRST, so level-order output needs no manual depth bookkeeping.
Fit a trend line inside one aggregate pass: regr_slope and regr_intercept return the least squares line, and regr_r2 reports how linear the relationship is.
Rebuild a bloated index with REINDEX CONCURRENTLY: writes keep flowing while the _ccnew replacement builds, and a failed run leaves an INVALID index to drop.
Enforce tenant isolation in the database with row level security: ENABLE plus FORCE ROW LEVEL SECURITY and a policy that compares tenant to a session setting.
Concatenate group members into one delimited string with STRING_AGG, ordering inside the aggregate and narrowing inputs with FILTER.
Empty tables fast with TRUNCATE RESTART IDENTITY, see why a foreign key reference blocks it, and use CASCADE plus a transaction for a safe purge.
Bucket amounts into equal-width ranges with WIDTH_BUCKET, which keeps out-of-range values in buckets 0 and n+1 rather than dropping them.