diff --git a/src/array/flatten.test.ts b/src/array/flatten.test.ts index 0e7c3fb..e2ab99e 100644 --- a/src/array/flatten.test.ts +++ b/src/array/flatten.test.ts @@ -1,17 +1,18 @@ import flatten from './flatten' describe('Flatten Array (flatten)', () => { - it('Flattens deeply nested sub arrays by default', () => { + it('should flatten deeply nested sub arrays by default', () => { + expect(flatten([[1, [2, [[3]]]], 4, [5, [[[6]]]]])).toEqual([1, 2, 3, 4, 5, 6]) expect(flatten([1, [2, 3], 4, [5, [6, [7, [8]]]]])).toEqual([1, 2, 3, 4, 5, 6, 7, 8]) }) - it('Flattens to a depth level when specified', () => { + it('should flatten to the specified depth level if provided', () => { const arr = [1, [2, 3], 4, [5, [6, [7]]], 8] expect(flatten(arr, 1)).toEqual([1, 2, 3, 4, 5, [6, [7]], 8]) expect(flatten(arr, 2)).toEqual([1, 2, 3, 4, 5, 6, [7], 8]) }) - it('Removes empty array items', () => { + it('should remove empty array items', () => { expect(flatten([1, 2, , 3, , 4, 5, [6, , 7], 8])).toEqual([1, 2, 3, 4, 5, 6, 7, 8]) }) }) diff --git a/src/array/flatten.ts b/src/array/flatten.ts index c3d67c5..2bc48b8 100644 --- a/src/array/flatten.ts +++ b/src/array/flatten.ts @@ -2,7 +2,7 @@ * * Creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. * - * @typeparam T The type of the items in the array. + * @typeparam T The type of the items in the array, specify this type parameter to avoid type widening on deeply nested arrays * @param array The array to be flattened. * @param depth The depth level specifying how deep a nested array structure should be flattened. Defaults to `Infinity`. * @return The flattened array. @@ -10,16 +10,16 @@ * @category array * * @example - * flattenDeep([1, [2, 3], 4, [5, [6, 7] ], 8]) + * flatten([1, [2, 3], 4, [5, [6, 7] ], 8]) * // Expected output: [1, 2, 3, 4, 5, 6, 7, 8] * */ -export default function flatten(array: Array, depth: number = Infinity): Array { - return array.reduce( - (accumulator: Array, value: T) => +export default function flatten(array: (T[][] | T[] | T)[], depth = Infinity): T[] { + return array.reduce( + (accumulator, value) => Array.isArray(value) && depth-- > 0 ? accumulator.concat(flatten(value, depth)) - : accumulator.concat(value), - [] + : accumulator.concat(value as T | T[]), + [], ) }