Normalize Unicode Before Comparing Strings
Normalize Unicode forms before comparing or searching, because composed and decomposed accents look identical but compare unequal.
Page 6 of 9
Normalize Unicode forms before comparing or searching, because composed and decomposed accents look identical but compare unequal.
Build rulers, indent levels, and progress bars with String.repeat: one call produces the whole run, zero repeats yield an empty string.
Repair lone surrogates with toWellFormed before persistence: isWellFormed detects them, U+FFFD replaces them, and matched pairs stay untouched.
static Symbol.hasInstance lets a class decide what instanceof returns, so duck-typed objects matching the expected shape pass without inheriting.
Symbol property keys stay invisible to Object.keys, for..in and JSON.stringify, and only getOwnPropertySymbols or Reflect.ownKeys can enumerate them.
Object-to-primitive conversion asks Symbol.toPrimitive first, then valueOf or toString depending on the hint, so numeric and string contexts can disagree.
A template element stores one row once; content.cloneNode(true) stamps out an independent row per record without building innerHTML strings.
Await any object with a then method: Promise.resolve and await unwrap thenables, and repeated resolve calls only take the first one.
timers/promises turns timers into awaitable promises: sleep reads linearly, setImmediate yields one macrotask turn, and setInterval iterates ticks that abort.
See why toFixed output follows the stored binary float instead of decimal rounding, then round money amounts predictably with Number.EPSILON.
trimStart removes leading whitespace, trimEnd removes trailing whitespace, trim does both; repeated calls stay idempotent on trimmed strings.
subarray returns a view over the same ArrayBuffer so writes land in the source array, while slice copies bytes into independent memory.
Guard untrusted JSON values with typeof plus a null check, then separate arrays from plain objects with Array.isArray because typeof reports both as object.
Validate URLs before constructing: canParse rejects bare protocol-relative strings, accepts opaque mailto schemes, and takes a base for relatives.
Scope resources with using declarations: [Symbol.dispose] runs in reverse declaration order on block exit, on both normal and throwing paths.
util.parseArgs validates declared flags: booleans default to false, string options can repeat into arrays, and positionals come back separately.
Hold objects weakly with WeakRef and observe collection via FinalizationRegistry: deref may still return the object until GC actually reclaims it.
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).
Collect async iterables into arrays with Array.fromAsync, which awaits every yielded value, accepts a per-item mapper, and works on sync iterables too.
Broadcast auth events with BroadcastChannel: one postMessage reaches every same-origin listener on the channel, delivery is asynchronous, close on teardown.
Preserve the root failure across rethrows with the Error cause option: outer context explains what happened while error.cause reaches the original TypeError.
Render dates through Intl.DateTimeFormat so field order, month names, and range collapsing come from the locale rules instead of hand-written format strings.
Render arrays as natural list text with Intl.ListFormat: long conjunction and disjunction styles, a narrow unit style, and formatToParts for custom markup.
Chain iterator helpers on generators and iterables: map, filter, and take build a lazy plan, toArray pulls, and every short-circuits on the first miss.
Extract typed fields from log lines with matchAll and named capture groups, so every match carries self-documenting keys instead of fragile array indexes.
Respond to late DOM writes with MutationObserver: subscribe to attribute and childList changes on a form, filter attributes, and disconnect on teardown.
Compare floats with a relative Number.EPSILON tolerance instead of ===, since binary rounding makes 0.1 + 0.2 differ from 0.3 by one resolution step.
Intercept config access with a Proxy: unknown keys throw on write to expose typos, reads fall back to defaults, and Reflect keeps base assignment intact.
Make any object consumable with for await by implementing Symbol.asyncIterator: next() returns a promise per step and callers can break out early.
Move between strings and UTF-8 bytes with TextEncoder and TextDecoder: fatal mode rejects invalid byte sequences while lenient mode substitutes U+FFFD.
Sort, reverse, and replace by index with toSorted, toReversed, and with — each returns a new array so readers of the original never observe a mutation.
Broadcast CustomEvent payloads through a shared EventTarget, the standard DOM event model, and let one-shot listeners remove themselves in their own handler.
Reach the most recent matching record with findLast and findLastIndex, which scan the array from the tail and return undefined or -1 when nothing matches.
Detect whether a caller set an option with Object.hasOwn, which ignores the prototype chain that the in operator walks and survives Object.create(null).
Run a batch of lookups with Promise.allSettled and partition fulfilled values from rejected reasons, so one failing item does not discard the rest of the batch.
Resolve with the first fulfilled task using Promise.any, and collect every rejection cause in AggregateError.errors only when all tasks fail.
Schedule callbacks with queueMicrotask and observe that microtasks run in enqueue order after synchronous code but before setTimeout timers get their turn.
Observe an element's content box with ResizeObserver instead of window resize events, writing measurements to data attributes and toggling classes.
Start independent tasks before awaiting them so durations overlap; completion order proves concurrency while the awaited array keeps start order.
Build, read, and mutate query strings with URLSearchParams: append and getAll handle repeated keys, set keeps one, and missing keys return null.
Attach per-object metadata through a WeakMap keyed by the object itself, so entries vanish with the key and the map cannot be enumerated.
Sort records by multiple keys with a composed comparator and rely on ES2019 sort stability so equal keys keep their input order.
Attach one listener on the list container and resolve targets with closest so dynamically added rows work without rebinding handlers.
Chain generator stages so data is pulled item by item on demand — memory stays flat for huge or infinite sources without arrays.
Format numbers, currencies, and percents with Intl.NumberFormat so locale-aware rendering needs zero manual thousand separators.
Find the leftmost position where a sorted array can accept a target using binary search with a lower-bound variant that returns insertion index for duplicates.
Generate a Gray code sequence of n bits using bit manipulation where consecutive values differ by exactly one bit.
Implement a bloom filter with k hash functions for probabilistic membership testing with a configurable false positive rate.
Implement a binary search tree supporting insert and delete where delete uses the in-order successor for two-child nodes.
Compute single source shortest paths in a weighted graph using Dijkstra algorithm with a binary min heap for efficient extraction.
Compute the Levenshtein edit distance between two strings with insert, delete, and substitute operations each costing one.
Find the shortest path in an unweighted graph using breadth first search with a predecessor map for path reconstruction.
Perform topological sort on a directed acyclic graph using depth first search with cycle detection via a tri-color marking scheme.
Implement a hash table with open addressing and double hashing for collision resolution supporting insert, lookup, and delete.
Sort an array by building a max heap in place then repeatedly extracting the maximum element to the end of the array.
Match a pattern in text using the Knuth Morris Pratt algorithm with a precomputed failure function for linear time matching.
Solve the 0-1 knapsack problem using dynamic programming with a one dimensional rolling array to reduce space complexity.
Compute the longest common subsequence of two strings using dynamic programming with full table reconstruction.
Count the number of inversions in an array using a modified mergesort that counts crossings during the merge step in O(n log n) time.
Generate all primes up to n using a segmented sieve of Eratosthenes for memory efficiency on large ranges.
Sort an array in place using quicksort with median-of-three pivot selection to avoid worst-case behavior on already sorted or reverse sorted input.
Find all occurrences of a pattern in text using the Rabin Karp algorithm with a rolling hash for O(n+m) average time complexity.
Implement a skip list supporting insert, delete, and search with probabilistic level assignment using geometric distribution.
Build a trie from a word list supporting prefix search and autocomplete suggestions ranked by word frequency.
Implement a disjoint set union find structure with path compression and union by rank for near constant amortized time.
Evaluate attribute-based access control policies over subject resource and action attributes for fine-grained authorization.
Configure an Apollo Client with in-memory cache error handling and typed queries for GraphQL data fetching.
Hash passwords with Argon2id using explicit memory time and parallelism parameters and verify with constant-time comparison.
Compose async generators into a pipeline for lazy streaming transformation with backpressure.
Implement an async mutex with FIFO fairness for exclusive access to shared resources without priority inversion.
Limit concurrent access to a resource with an async semaphore supporting acquire release and run helpers.
Add a response cache interceptor to Axios with TTL and cache key normalization for idempotent GET requests.
Apply exponential backoff retry to async methods via a decorator with per-method configuration and error filtering.
Collect items into a batch and flush by size threshold or timer whichever fires first for efficient bulk API submission.
Configure a BullMQ job queue on Redis with retry backoff concurrency and dead letter handling.
Create a generator that yields fixed-size chunks from an array for memory-efficient batch processing.
Implement a circuit breaker with closed open and half-open states that probes recovery with a single trial call before full traffic.