| 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 (const item of arr) { | |
| 24 | // Edge Case: Skip null and undefined values | |
| 25 | if (item === null || item === undefined) { | |
| 26 | continue; | |
| 27 | } | |
| 28 | ||
| 29 | // Edge Case: Recursively flatten nested arrays | |
| 30 | if (Array.isArray(item)) { | |
| 31 | const flattened = flatten(item); | |
| 32 | result.push(...flattened); | |
| 33 | } else { | |
| 34 | result.push(item); | |
| 35 | } | |
| 36 | } | |
| 37 | ||
| 38 | return result; | |
| 12 | 39 | }; |
| 40 | ||
| 41 | // Handled Edge Cases: null input, undefined input, non-array input, null values in array, undefined values in array, nested arrays of any depth |