WebCrypto AES-GCM Encrypts And Decrypts
Encrypt and decrypt with WebCrypto AES-GCM, seeing the 16-byte authentication tag and verifying that tampered ciphertext is rejected.
Page 4 of 9
Encrypt and decrypt with WebCrypto AES-GCM, seeing the 16-byte authentication tag and verifying that tampered ciphertext is rejected.
Print nested objects with util.inspect using depth, compact, and breakLength options so log lines stay single-line and deep structures stay readable.
Wrap terminal text with util.styleText; validateStream defaults to true so ANSI is emitted only when stdout can render colors; pass false to always wrap.
Compress UTF-8 text with gzipSync and restore it with gunzipSync, verifying the round trip is byte-identical and reporting the size reduction.
Diffing two snapshots with Sets answers which items arrived and which left, so change feeds and cache invalidation can react to exact deltas.
Array.of(7) builds a one-element array while new Array(7) reserves seven empty slots, and Array.of stays a generic factory when borrowed with call.
A concurrency-capped task queue gains pause() to hold new starts, resume() to continue them, and drain() that resolves once nothing runs or waits.
A fixed pool recycles connections: acquire resolves immediately or parks the caller FIFO, and release hands the resource to the longest-waiting job.
matches tests the element itself against a selector, closest walks up through ancestors from itself, and both return null when nothing matches.
animate() starts a Web Animation immediately, returning an Animation object whose playState, currentTime, and finished promise give full programmatic control.
Seven values are falsy while empty arrays and objects are truthy, so filter(Boolean) compacts lists and || versus ?? treat missing defaults differently.
for...in walks string keys including enumerable extras, for...of reads elements through the iterator protocol, and plain objects need Object.entries for of.
A label lets continue restart the outer loop and break leave both loops at once, where an unlabeled break only exits the innermost iteration.
??= writes only for nullish values, ||= for falsy ones and &&= for truthy ones, and the right-hand expression is skipped entirely when the guard fails.
== converts both sides before comparing so strings, arrays and booleans can equal numbers, while === never converts and Object.is alone finds NaN.
Map.delete removes one key and reports whether it existed while clear drops everything at once, and setting a value to undefined keeps the key present.
Concatenating map entries lets later layers win, and a resolveConflict callback upgrades the merge into a per-key policy for layered configuration.
Rebuilding each level along a changed path with spread keeps untouched branches reference-identical, so equality checks and memoization stay cheap.
Insertion-order keys make equal objects serialize differently; recursively sorting keys before JSON.stringify yields one canonical string per value.
Primitives get wrapper methods through temporary boxing, but values created with new are objects: different typeof, strict equality fails, Symbol refuses new.
instanceof answers true for every ancestor on the prototype chain, Object.getPrototypeOf walks it hop by hop, and hasOwn ignores inherited members entirely.
scrollTop plus clientHeight against scrollHeight reports the pixels remaining to the bottom, the signal infinite scroll uses before fetching more rows.
selectionStart and selectionEnd expose the highlighted span inside an input, while getSelection with a Range reads text selected anywhere on the page.
split accepts a regex so alternation splits on several separators at once, capture groups keep the separators, and the limit argument caps the piece count.
substring clamps out-of-range and negative indices and swaps reversed arguments, while slice counts negatives from the end and returns an empty string instead.
switch compares with strict equality so a string status never hits a number case, and deliberately omitted breaks group neighboring cases into one branch.
toPrecision keeps a total digit count and switches to exponential notation when digits run out, while toFixed pins decimal places and never abbreviates.
finally always runs after try or catch, a return written inside it replaces the value already computed, and local changes there cannot alter a settled result.
Cancel stale requests with AbortController so a fast typist does not let an older response overwrite the newest one.
Move an ArrayBuffer into a larger buffer with transfer, confirm the source detaches, and inspect the zero-filled tail.
Compress and decompress strings with CompressionStream and DecompressionStream, piping through Blob so no third-party codec is needed.
Hash UTF-8 text with crypto.subtle.digest, convert the digest to hex, compare repeated and case-changed inputs, and check the fixed length.
Register a custom element and use connectedCallback and attributeChangedCallback to render content and react to attribute updates.
Build timestamps with Date.UTC so month math and comparisons stay independent of the machine time zone, then format and parse them.
Define getter and setter descriptors with Object.defineProperty to validate writes and expose computed values without leaking internals.
Register cleanup with DisposableStack defer, use, and adopt, then dispose once and watch callbacks run in reverse order.
Build a tiny pub/sub with EventTarget and CustomEvent so modules communicate through real events instead of ad-hoc callbacks.
Open an IndexedDB database, write records in one transaction, and read them back by key with a small promise wrapper around events.
Render dates for a locale and turn instants into relative phrases with Intl.DateTimeFormat and RelativeTimeFormat.
Normalize and deduplicate BCP 47 tags with Intl.getCanonicalLocales, catch invalid tags, and feed the result to a formatter.
Use Intl.Locale maximize and minimize to resolve likely subtags, then attach calendar and numbering options to the tag.
Format measurements with Intl.NumberFormat unit style, switch display modes, and use formatToParts to separate the number from its unit.
List calendars, units, currencies, and time zones with Intl.supportedValuesOf, then feed a supported unit into NumberFormat.
Implement Symbol.iterator so your own objects work with for-of, spread, and destructuring — the same protocol as built-in collections.
Group records with Map.groupBy using object keys, compare identity with a structural clone, and contrast the result with Object.groupBy string keys.
Traverse possibly-missing data with optional chaining and fall back with nullish coalescing so falsy values are not clobbered.
Collect every outcome with Promise.allSettled when a batch must not fail as a whole, then branch on fulfilled versus rejected.
Intercept writes with a Proxy set trap so invalid assignments fail loudly at the mutation site instead of corrupting state silently.
Batch many rapid updates into one flush by scheduling work on the microtask queue so renders and network calls stay coalesced.
Adapt a sync generator into a web ReadableStream with ReadableStream.from, then consume it with async iteration.
Branch one ReadableStream into two independent readers with tee, then drain both branches concurrently.
Call Reflect.construct with a different newTarget to borrow a constructor while producing an instance of a subclass prototype.
Enable the d flag on regular expressions so every match exposes start and end indices for the whole pattern and each capture group.
Use the RegExp v flag to subtract and intersect Unicode character sets, combine script properties, and validate identifiers with set notation.
Create a Request from a URL and options, clone it before reading the body, and inspect method, headers, and cache mode without sending traffic.
Clone a Response before reading its body so one consumer parses JSON while another reads text, and observe what happens on re-read.
Build Windows paths and regex patterns with String.raw tagged templates, comparing raw backslashes against normal escapes.
Clone nested data with structuredClone instead of JSON round-trips — Dates, Maps, Sets, and cycles survive the copy intact.
Override Symbol.hasInstance to accept plain objects by shape, then filter mixed samples through the custom instanceof check.
Use toSpliced to insert, remove, and replace array elements while returning a new array, leaving the original list untouched.
Match Greek script, numbers, letters, and pictographs with Unicode property escapes, including the required u flag.
Validate absolute and relative URLs with URL.parse, return null instead of throwing, and read host, port, and query values.
Compose URLs with the URL API and searchParams so encoding, duplicate keys, and relative bases are handled by the platform.
Serialize work across tabs with navigator.locks.request, so two tabs never write the same storage key at the same moment.
Build a WritableStream with write, close, and abort handlers, pipe a ReadableStream into it, and collect the transformed chunks.
AbortSignal.any fires when the first source aborts and adopts its reason, so a request can honor both a deadline and a user-initiated stop from one signal.
toSorted, toReversed, toSpliced and with return new arrays and leave the source intact, replacing the mutate-then-clone pattern around shared state.
Splitting argv into booleans flags, --key=value pairs and positionals, with -- ending option parsing, covers most CLIs before reaching for a parser library.
Every control posts as a string, but number and range inputs expose valueAsNumber, checkboxes carry a value attribute, and validity maps failed rules.
A rejection skips every then until one catch; handlers after the catch resume normally, and finally runs on both paths without changing the settled value.
Compose filter, map, flat, and reduce into readable data pipelines that replace hand-rolled loops for everyday list processing.
Hide instance state in a module-scoped WeakMap so properties stay unreachable from outside while garbage collection stays automatic.
Map compares object keys by reference, so multi-field lookups need one keyOf helper turning tenant, user, and day into a stable string key.
Tally labeled calls with console.count, nest logs with group and groupEnd, measure spans with time and timeEnd, and assert only prints on failure.
crypto.randomUUID produces RFC 4122 v4 identifiers with 122 random bits, version and variant nibbles fixed by the spec at known positions.
Check the clock before each item, stop the moment a time budget runs out, and hand the untouched tail to the next tick instead of timing out mid-item.
Without a comparator, sort stringifies elements and orders them by code units, so 10 lands before 2; numeric arrays need a subtraction comparator.
Assemble rows on a detached fragment and attach once, so the document sees a single insertion; the fragment itself never enters the tree.
Keep Tab cycling inside a container by listening for keydown and focusing the next or previous focusable, wrapping at both ends.
getMonth returns 0-11 and getDay puts Sunday at 0, so labels need lookup tables and month 12 in the constructor rolls into the next year.
Drop marks around work and read the spans back with measure; entries stay buffered for later inspection instead of ad hoc timing prints.
Object.keys and JSON.stringify skip symbol keys, so cloning or auditing whole records needs Reflect.ownKeys, the only builtin that lists every own key.
Dollar sequences like $1, $&, and $<name> expand inside replacement strings; function replacements return literal text with no expansion at all.
Read the high-resolution timestamp in each frame callback, clamp long gaps after background tabs, and stop the loop on a frame budget.
Integers beyond 2^53 lose exactness, so Number.isSafeInteger guards both inputs and results before IDs or amounts enter arithmetic.
Steps that consume the previous result must await in order, while unrelated calls belong in the same Promise.all so they run alongside the chain.
The [object X] label from Object.prototype.toString reads Symbol.toStringTag, so custom classes can brand their diagnostics without touching instanceof.
Compile route templates once and exec or test requests against them, extracting named groups and rejecting wrong hosts without hand-parsing.
AbortSignal.timeout builds a deadline signal that aborts itself with a TimeoutError; wire it into slow work with throwIfAborted and one abort listener.
FormData.entries yields every field and file as insertion-ordered pairs, while has/get/delete probe individual entries before a POST goes out.
Wire a two-way MessageChannel and transfer an ArrayBuffer through postMessage: the receiver decodes the bytes while the sender side reads length zero.
padEnd left-aligns names while padStart right-aligns numbers, producing fixed-width report columns; over-wide values are never truncated.
Promise.all rejects as soon as any member rejects, abandoning slower pending results, while allSettled waits for every member and aligns statuses by position.
Fold an array into a Map of per-key aggregates in one pass: the Map keeps first-seen order, and the object-spread version exposes a per-iteration copy trap.
structuredClone deep-copies Maps, Sets, and Dates that JSON.stringify drops, and its transfer option moves ArrayBuffer ownership instead of copying bytes.
Parse untrusted markup through a programmatic template: scripts never run, event-handler attributes stay inert, and content.cloneNode yields a disjoint tree.
Wire cleanup into scoping with using: the runtime calls Symbol.dispose on block exit in reverse order, and the error path disposes before the throw propagates.
A visually hidden aria-live region announces async outcomes to screen readers; clear it before writing so repeated messages are spoken again.
Await a one-shot event with events.once instead of wiring resolve callbacks by hand, and pass an AbortSignal so a listener that never fires cannot hang.
Disable a whole form with one fieldset.disabled flag during submission, and release it in finally so a failed gateway never leaves the form locked.