Skip to content

Commit 46c09d8

Browse files
feat: add array flatten algorithm
1 parent 5c39e87 commit 46c09d8

2 files changed

Lines changed: 73 additions & 0 deletions

File tree

‎Data-Structures/Array/Flatten.js‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* @function flatten
3+
* @description Flattens a nested array into a single-level array.
4+
* Supports both shallow (depth=1) and deep flattening.
5+
* @param {Array} arr - The nested array to flatten
6+
* @param {number} depth - The depth to flatten (default: Infinity)
7+
* @returns {Array} - The flattened array
8+
* @see https://en.wikipedia.org/wiki/Flat_array
9+
* @example flatten([1, [2, [3, [4]]]]) => [1, 2, 3, 4]
10+
* @example flatten([1, [2, [3]]], 1) => [1, 2, [3]]
11+
*/
12+
const flatten = (arr, depth = Infinity) => {
13+
if (!Array.isArray(arr)) {
14+
throw new TypeError('Input must be an array')
15+
}
16+
if (!Number.isInteger(depth) && depth !== Infinity) {
17+
throw new TypeError('Depth must be an integer or Infinity')
18+
}
19+
if (depth === 0) return [...arr]
20+
return arr.reduce((flat, item) => {
21+
if (Array.isArray(item) && depth > 0) {
22+
return flat.concat(flatten(item, depth - 1))
23+
}
24+
return flat.concat(item)
25+
}, [])
26+
}
27+
28+
export { flatten }
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { flatten } from '../Flatten.js'
2+
3+
describe('flatten', () => {
4+
test('flatten([1, 2, 3]) returns [1, 2, 3]', () => {
5+
expect(flatten([1, 2, 3])).toEqual([1, 2, 3])
6+
})
7+
8+
test('flatten([1, [2, 3]]) returns [1, 2, 3]', () => {
9+
expect(flatten([1, [2, 3]])).toEqual([1, 2, 3])
10+
})
11+
12+
test('flatten deeply nested array', () => {
13+
expect(flatten([1, [2, [3, [4]]]])).toEqual([1, 2, 3, 4])
14+
})
15+
16+
test('flatten with depth 1', () => {
17+
expect(flatten([1, [2, [3]]], 1)).toEqual([1, 2, [3]])
18+
})
19+
20+
test('flatten with depth 0 returns same array', () => {
21+
expect(flatten([1, [2, [3]]], 0)).toEqual([1, [2, [3]]])
22+
})
23+
24+
test('flatten empty array returns empty array', () => {
25+
expect(flatten([])).toEqual([])
26+
})
27+
28+
test('flatten with mixed types', () => {
29+
expect(flatten([1, ['a', [true, [null]]]])).toEqual([1, 'a', true, null])
30+
})
31+
32+
test('flatten does not mutate original array', () => {
33+
const arr = [1, [2, [3]]]
34+
flatten(arr)
35+
expect(arr).toEqual([1, [2, [3]]])
36+
})
37+
38+
test('throws TypeError for non-array input', () => {
39+
expect(() => flatten('123')).toThrow(TypeError)
40+
})
41+
42+
test('throws TypeError for invalid depth', () => {
43+
expect(() => flatten([1, 2], 1.5)).toThrow(TypeError)
44+
})
45+
})

0 commit comments

Comments
 (0)