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