Skip to content

Commit

Permalink
feat(flatten): update flatted type signature to allow for atleast sin…
Browse files Browse the repository at this point in the history
…gle level nested sub-arrays
  • Loading branch information
cahilfoley committed May 26, 2019
1 parent adc1263 commit 8eb0efc
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 10 deletions.
7 changes: 4 additions & 3 deletions src/array/flatten.test.ts
Original file line number Diff line number Diff line change
@@ -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])
})
})
14 changes: 7 additions & 7 deletions src/array/flatten.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,24 @@
*
* 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.
*
* @category array
*
* @example
* flattenDeep([1, [2, 3], 4, [5, [6, 7] ], 8])
* flatten<number>([1, [2, 3], 4, [5, [6, 7] ], 8])
* // Expected output: [1, 2, 3, 4, 5, 6, 7, 8]
*
*/
export default function flatten<T>(array: Array<T>, depth: number = Infinity): Array<T> {
return array.reduce(
(accumulator: Array<T>, value: T) =>
export default function flatten<T>(array: (T[][] | T[] | T)[], depth = Infinity): T[] {
return array.reduce<T[]>(
(accumulator, value) =>
Array.isArray(value) && depth-- > 0
? accumulator.concat(flatten(value, depth))
: accumulator.concat(value),
[]
: accumulator.concat(value as T | T[]),
[],
)
}

0 comments on commit 8eb0efc

Please sign in to comment.