splice Removes And Inserts In Place
splice returns the removed elements as a typed array, deletes or replaces in place, and index beyond length is a silent no-op on an empty result.
Page 4 of 50
splice returns the removed elements as a typed array, deletes or replaces in place, and index beyond length is a silent no-op on an empty result.
toSorted returns a new sorted array and accepts readonly inputs, so ranking views never reorder the source and nested tuples stay fully typed.
Array.prototype.with returns a copy with one index replaced, accepts negative indices, throws RangeError beyond length, and keeps the source untouched.
Replace the manual for-i-less-than-b.N loop with b.Loop on Go 1.24: iteration count, timer reset, and memory stats are handled automatically.
Decompress an embedded bzip2 stream with compress/bzip2, whose streaming reader needs no output size — the package ships decompression only.
Compress and decompress bytes with compress/lzw, where the byte order and literal width are parameters that both ends must share.
Classify context errors with errors.Is: canceled callers, exceeded deadlines, and healthy contexts each report a distinct outcome.
Build cmd.Env from os.Environ plus overrides so children see staged configuration, and filter secrets out of the inherited environment before spawn.
Split PATH-style environment values with filepath.SplitList, which uses the OS list separator, and rejoin them without guessing the delimiter.
Register a flag whose parsing logic is a plain callback with flag.Func, so repeatable values accumulate without a custom flag.Value type.
Compare floats through a small epsilon instead of ==, since 0.1+0.2 != 0.3 while positive infinity still equals itself.
Implement fmt.Formatter so Printf hands your type the verb and flags, letting it render its own %v, %+v, and %q output.
Encode interface-valued fields with gob by registering each concrete type, so the decoder can rebuild the right variant from the transmitted name.
Turn panics into errors by recovering in a deferred function and switching on the panic value: runtime errors implement error, strings stay strings.
Implement fmt.GoStringer so the %#v verb prints a redacted summary for credential-bearing types instead of leaking password fields into debug logs.
Unmarshal into any and type-switch on map[string]any, []any, float64, and string branches to inspect JSON whose structure is only known at runtime.
Accept payloads that arrive as an {"orders": [...]} envelope or a bare array by trying two Unmarshal targets in order and falling back cleanly.
Intersect two count bags with min-per-item so shared stock reflects overlapping quantities, not just which names both maps contain.
Aggregate tickets into map[string]map[string]int keyed by region then status, sorting outer keys because map range order is randomized.
Compute MD5 digests with crypto/md5 in one-shot and streaming forms, and keep the warning: known collisions make it unfit for any security purpose.
Parse and build host:port pairs with netip.AddrPort, keeping address and port as typed fields instead of splitting strings by hand.
Pick url.PathEscape for a single path segment and url.QueryEscape for a query value, since the two sets of reserved characters differ.
Show the unsynchronized counter that the race detector flags under go run -race, and the mutex-guarded version that converges on the same workload.
Write struct fields by name with reflect.Value.FieldByName after CanSet and AssignableTo checks, so generic form or config binding fails with clear errors.
Build every (size, color) pair from two slices with a generic cross product helper, not just the index-aligned pairs that zip produces.
Take head and tail windows of at most n items with clamping, and see that the windows remain views into the same backing array.
Split one slice into info and warn groups with two append targets, preserving original order in each group without mutating the source.
Reorder items by an index permutation after validating length and uniqueness, so bad indices fail before any element is moved.
Walk two slices with one index per side to test whether a short sequence appears in order inside a longer event stream.
Deduplicate records by a projected key — lowercased email — keeping each first occurrence instead of requiring exact whole-value equality.
Rewrite JSON log fields with slog.HandlerOptions.ReplaceAttr: rename the time key, lowercase levels, and redact sensitive keys before they reach output.
Locate a target in sorted data with sort.Find, whose three-way cmp returns the same signs as strings.Compare and reports the exact insert point on a miss.
Store signed integers in one to ten bytes with binary.PutVarint, and walk the buffer back with binary.Varint to recover each value and its width.
Bytes store -128..127, so anything above 127 wraps negative; & 0xFF widens to an unsigned int for CRC, hashing, and wire-format work.
Implement a custom Collector whose combiner folds two Welford accumulators, so parallel streams land on the same sample variance as the sequential run.
Accept month names in any letter case by building a DateTimeFormatter with parseCaseInsensitive instead of upper-casing the input yourself first.
Flip Windows hidden and read-only flags on a file through DosFileAttributeView, then prove the read-only attribute rejects rewrites until you clear it.
Group files from a directory walk by a size-plus-SHA-256 fingerprint so only true byte-level duplicates survive the grouping.
Tier.values() hands back a new array on every call, so callers mutate their own copy while the shared constant list stays intact; cache it for hot paths.
Vector.elements() returns an Enumeration; asIterator and Collections.list bridge it into for-each and the Stream API without rewriting legacy code.
Files.list and Files.walk return DirectoryStream-backed streams that terminal ops never close; wrap every walk in try-with-resources or leak handles.
A blocked channel read on a socket responds to interrupt by closing the channel and raising ClosedByInterruptException instead of returning.
find() resumes at the previous match end, so overlapping hits are invisible; restarting find from start+1 reveals every occurrence.
The default percent instance rounds to whole percents; setMaximumFractionDigits restores decimals and parse turns 43.21% back into the ratio 0.4321.
One call site with long, Integer, and int... overloads shows resolution order: widening beats boxing beats varargs, so pick(1) lands on long.
One getPathMatcher call serves both syntaxes: glob: patterns cross directories with ** while regex: matches paths with a plain regular expression.
Poll new entries into a bounded min-heap of size k: overflow evicts the smallest survivor, and a final sort turns the heap into a ranked list.
ProcessBuilder.environment() inherits the parent environment and accepts overrides, so a child process receives staged config without editing global state.
A compact constructor takes defensive copies of mutable fields, so later caller mutations never leak into the record and accessors hand out immutable lists.
Encrypt and decrypt payloads with RSA-OAEP via Cipher, passing an explicit OAEPParameterSpec so the digest and MGF1 hash never depend on provider defaults.
Count character frequencies and sum -p log2 p to score repeat-heavy strings near zero bits per character — a rough signal, not a security verdict.
shutdownOutput closes only the write direction: the peer sees a clean EOF, finishes its read loop, and can still send its final reply back.
Show that an instance monitor never blocks the class monitor: code holding one object lock runs while the static critical section proceeds concurrently.
Strip ANSI escape sequences from colored CLI output with one regex covering CSI, OSC, and two-byte controls, leaving plain text untouched.
Derive HOTP and TOTP one-time codes from HMAC-SHA1 with dynamic truncation, checking the published RFC 4226 and RFC 6238 test vectors end to end.
Bound virtual thread concurrency with a Semaphore: tasks fan out cheaply while the permit count caps simultaneous in-flight downstream calls.
Cap ZipInputStream entries with a streaming byte budget: declared sizes can be unknown, so count every read and abort the moment an entry overshoots.
focus() and blur() update document.activeElement immediately, blur falls back to body, and document.hasFocus() reports whether the page owns the keyboard.
every() returns true for an empty array because no item can contradict the rule; gate empty input explicitly instead of inheriting the vacuous default.
textContent concatenates every text node including style rules and hidden spans, while innerText approximates rendered output and drops what CSS hides.
The for attribute and label wrapping both connect a label to its control; element.labels stays live and htmlFor re-points the association on assignment.
Each request records a sequence ticket and responses check it before applying, so type-ahead searches drop stale results instead of flashing old data.
Plain function calls leave new.target undefined, so constructors can throw a clear error, and the same check lets base classes reject direct instantiation.
Object.entries pairs keys with values and Object.fromEntries rebuilds the record, so per-value transforms and key renames run without hand-written loops.
querySelectorAll(':scope > li') pins matching to direct children of the node, while a bare selector keeps matching descendants at every nesting depth.
Comparators returning booleans only produce 0 or 1, so descending swaps never apply; subtract the fields instead to get a numeric comparator.
Long-running loops cannot be interrupted from outside, so cooperative work calls signal.throwIfAborted() between steps to stop cleanly on abort.
typeof classifies null as object because of a legacy type tag, so branches that trust typeof must check value === null separately to catch unset values.
Split CPU-heavy work into chunks and await a setTimeout macrotask between them so timers and I/O run; await Promise.resolve() only drains microtasks.
click only fires for the primary button; auxclick handles middle and unclaimed secondary presses, which is where custom middle-click link behavior belongs.
await returns an array literal untouched, so its promise elements stay pending; Promise.all actually waits for every element and keeps the original order.
Buffer.from(value, "hex") silently stops at the first invalid character pair instead of throwing; untrusted hex must be shape-checked first.
FocusEvent.relatedTarget names the element about to receive focus, letting an open menu tell a genuine move inside the widget from a real focus-out to the page.
getModifierState('CapsLock') reports the physical lock state at keydown time, so password fields can surface a caps-lock hint without tracking keyup.
JSON.parse defines __proto__ as an ordinary own property, but assigning that key hits the setter and hijacks the target object, so merges must reject it.
Held keys re-fire keydown with event.repeat set to true, so guarding on repeat keeps one physical press equal to one action instead of dozens of toggles.
Map.forEach passes (value, key) in the opposite order of Object.entries, and JSON.stringify of a Map yields {}, so convert through Object.fromEntries first.
matchAll throws TypeError without the /g flag because a non-global regex would match forever; it iterates a clone, so the original lastIndex stays untouched.
navigator.connection exposes effectiveType, saveData and rtt on Chromium; feature-detect it, honor saveData first, then pick assets by measured network quality.
Object.assign skips null and undefined sources, overwrites keys layer by layer, and mutates only its first argument, so pass {} first to keep defaults intact.
wheel deltas arrive in pixels, lines, or pages depending on deltaMode; multiplying by a fixed unit per mode keeps custom scrolling consistent across devices.
doctest.testmod executes every >>> example in docstrings and compares printed results, turning documentation into tests that catch drift.
East Asian wide glyphs occupy two terminal cells, so column padding must measure display width with unicodedata.east_asian_width before ljust.
Maintain prefix sums with index & -index jumps so point updates and range queries cost O(log n) each, and changed entries never force a full rescan.
Sort edges by weight, union the endpoints when their roots differ, and stop after n-1 picks: the result is a minimum spanning tree with cycle rejection.
Track one OrderedDict bucket per use frequency and evict the oldest key at the lowest frequency, promoting keys on every get and put.
os.scandir yields DirEntry objects that carry scan data, so is_dir() and stat() skip the extra syscall per file that os.listdir would need.
Store range sums in a 4n array indexed like a binary tree so point updates and arbitrary range queries both cost O(log n) without rescanning elements.
Postfix expressions evaluate with one stack: push numbers, pop two operands per operator, and the final remainder is the whole expression's value.
correlation() returns the Pearson coefficient between two series while covariance() keeps raw units; self-correlation is 1 and linear rescaling preserves r.
tokenize.generate_tokens applies lexical rules, so COMMENT tokens never include # characters that live inside string literals.
patch() swaps the module-level datetime name for a Mock whose now() returns an injected moment, so both greeting branches run without a real clock.
fmean applies weights, harmonic_mean averages equal-distance speeds honestly, and geometric_mean fits growth factors like 2x then 8x.
to_mut converts the borrowed Cow into an owned buffer only when a write happens, and into_owned returns a String either way.
Hand strings to C code through CString: interior NUL bytes are rejected with the offending bytes, and valid values carry exactly one terminating NUL.
Group 31-day months with or-patterns, 30-day months with another arm, and let February branch on the leap-year rule inside the match.
Enforce duration budgets with checked_add and checked_sub, which return Option instead of wrapping past zero the way Duration cannot go negative.
Break a Duration into hours, minutes, and seconds for human readable CLI output, since Debug prints machine units like 90061s.
match destructures a recursive Value enum, printing arrays and nested objects with growing indentation until every leaf has been visited.
try_new returns Result<Self, String> so invalid port numbers become construction-time errors instead of broken values circulating in memory.