RangeError: Maximum call stack size exceeded when calling core-js Array.flat on deeply nested arrays
0 reputation · 22 Feb 2024, 03:45 UTC
0 reputation · 22 Feb 2024, 03:45 UTC
When using the core-js polyfill for Array.prototype.flat on deeply nested arrays, a RangeError: Maximum call stack size exceeded can be thrown. The polyfill implements a recursive algorithm that follows the ES2022 specification, but it does not guard against stack overflow on highly nested structures.
core-js preserves holes in sparse arrays during flattening, matching the spec. However, older polyfills replace holes with undefined. There is no consensus on whether the polyfill should maintain holes or convert them, and the iterative patch that avoids recursion is not enabled by default.
Array.flat polyfill be modified to replace holes with undefined to align with some legacy polyfills, or should it continue preserving holes as per the ES2022 spec?RangeError on deeply nested arrays, and what API surface would expose this configuration?34275 reputation · 22 Feb 2024, 07:44 UTC
The RangeError: Maximum call stack size exceeded occurs when the core‑js polyfill for Array.prototype.flat uses a recursive helper that exceeds the JavaScript call‑stack limit on deeply nested arrays.
flat recursively.npm list core-js or inspect package.json).npm install core-js@latest.flat() with an iterative flattening utility (e.g., lodash.flatDepth or a simple loop‑based function).node --stack-size=65536, but this is not a production‑safe fix.Please confirm your current core-js version so the advice can be tailored to your situation.
Use comments to ask for clarification. Post a solution as an answer.
34,275 reputation · 22 Feb 2024, 07:38 UTC
If you see a RangeError: Maximum call stack size exceeded when calling Array.prototype.flat, the polyfill is likely being used because the environment lacks a native flat method. You can confirm this by logging Array.prototype.flat.toString(); a native method shows the text "[native code]", whereas the core-js polyfill will display its source.
Upgrading to core-js ≥ 3.21.0 replaces the recursive implementation with an iterative one that avoids the stack overflow, but ensure your lockfile actually resolves to that version (e.g., npm list core-js or inspect yarn.lock or package-lock.json). If you remain on an older version and cannot upgrade, replace the call with a user‑land iterative flattening utility or import the standalone core-js/es/array/flat from a newer release.