| 4 | 4 | // |
| 5 | 5 | |
| 6 | 6 | /** |
| 7 | | * @param {any[]} arr |
| 8 | | * @returns {any[]} |
| 7 | * Flattens a nested array of any depth, excluding null and undefined values. |
| 8 | * |
| 9 | * @param {any[]} arr - The nested array to flatten |
| 10 | * @returns {any[]} - A flattened array with no nested arrays and no null/undefined values |
| 9 | 11 | */ |
| 10 | 12 | export const flatten = (arr) => { |
| 11 | | throw new Error('Remove this line and implement the function'); |
| 13 | // Edge Case: Handle when input is not an array |
| 14 | if (!Array.isArray(arr)) { |
| 15 | // If it's null or undefined, exclude it |
| 16 | if (arr === null || arr === undefined) { |
| 17 | return []; |
| 18 | } |
| 19 | // If it's a primitive value, return it in an array |
| 20 | return [arr]; |
| 21 | } |
| 22 | |
| 23 | const result = []; |
| 24 | |
| 25 | for (const item of arr) { |
| 26 | // Edge Case: Skip null and undefined values |
| 27 | if (item === null || item === undefined) { |
| 28 | continue; |
| 29 | } |
| 30 | |
| 31 | // Edge Case: If item is an array, recursively flatten it |
| 32 | if (Array.isArray(item)) { |
| 33 | const flattened = flatten(item); |
| 34 | result.push(...flattened); |
| 35 | } else { |
| 36 | // Edge Case: If item is a primitive value, add it to result |
| 37 | result.push(item); |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | return result; |
| 12 | 42 | }; |
| 43 | |
| 44 | // Handled Edge Cases: |
| 45 | // 1. Input is not an array |
| 46 | // 2. Input contains null or undefined values |
| 47 | // 3. Input contains nested arrays of any depth |
| 48 | // 4. Input contains primitive values |