| 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 when input is not an array | |
| 12 | if (!Array.isArray(arr)) { | |
| 13 | return []; | |
| 14 | } | |
| 15 | ||
| 16 | const result = []; | |
| 17 | ||
| 18 | for (const item of arr) { | |
| 19 | // Edge Case: Skip null and undefined values | |
| 20 | if (item === null || item === undefined) { | |
| 21 | continue; | |
| 22 | } | |
| 23 | ||
| 24 | // Edge Case: If item is an array, recursively flatten it | |
| 25 | if (Array.isArray(item)) { | |
| 26 | const flattened = flatten(item); | |
| 27 | result.push(...flattened); | |
| 28 | } else { | |
| 29 | // Edge Case: If item is a primitive value, add it to result | |
| 30 | result.push(item); | |
| 31 | } | |
| 32 | } | |
| 33 | ||
| 34 | return result; | |
| 12 | 35 | }; |
| 36 | ||
| 37 | // Handled Edge Cases: input is not an array, null values, undefined values, nested arrays of any depth, primitive values |