📋 Array.prototype.flat() Polyfill
Category: js / polyfills
Difficulty: medium
The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. This polyfill provides both a simple recursive solution and a spec-compliant depth-aware implementation. ✅ Simple Recursive Implementation [code example] 📌 Example [code example] 🧠 Atom-of-Thoughts Breakdown Base Case: If the item is not an array , push it to the result. Recursive Case: If the item is an array , call flattenRecursive() on it, and concatenate its result. Accumulator: Uses a local result array to collect all flattened items. 🧪 Handles: Arbitrary nesting: ✅ Mixed types: ✅ Empty arrays: ✅ Here’s a spec-compliant polyfill for Array.prototype.flat , matching ECMAScript behavior: ✅ Flat Polyfill (Depth-Aware) [code example] 📌 Usage [code example] 🧠 Atom-of-Thoughts Breakdown Default depth = 1 for single-level flattening. Recursive helper flatten(arr, d) : If item is array and depth > 0 → recurse with depth - 1. Else → push item to result. Uses closure result[] to accumulate flattened values. 🧪 Edge Case Behavior Output [1, 2, 3] [1, [2, [3]]]with depth=1 [1, 2, 3] [1, [2, [3]]]with depth=0...