| 8 | 8 | * @returns {any[]} |
| 9 | 9 | */ |
| 10 | 10 | export const flatten = (arr) => { |
| 11 | throw new Error('Remove this line and implement the function'); | |
| 11 | // Edge Case: Handle null or undefined input | |
| 12 | if (arr === null || arr === undefined) { | |
| 13 | return []; | |
| 14 | } | |
| 15 | ||
| 16 | // Edge Case: Handle non-array input | |
| 17 | if (!Array.isArray(arr)) { | |
| 18 | return []; | |
| 19 | } | |
| 20 | ||
| 21 | const result = []; | |
| 22 | ||
| 23 | for (let i = 0; i < arr.length; i++) { | |
| 24 | const element = arr[i]; | |
| 25 | ||
| 26 | // Edge Case: Skip null or undefined elements | |
| 27 | if (element === null || element === undefined) { | |
| 28 | continue; | |
| 29 | } | |
| 30 | ||
| 31 | // Edge Case: Recursively flatten nested arrays | |
| 32 | if (Array.isArray(element)) { | |
| 33 | const flattened = flatten(element); | |
| 34 | for (let j = 0; j < flattened.length; j++) { | |
| 35 | result.push(flattened[j]); | |
| 36 | } | |
| 37 | } else { | |
| 38 | result.push(element); | |
| 39 | } | |
| 40 | } | |
| 41 | ||
| 42 | return result; | |
| 12 | 43 | }; |
| 44 | ||
| 45 | // Handled Edge Cases: null/undefined input, non-array input, null/undefined elements, nested arrays |