Created
November 20, 2018 23:41
-
-
Save horaciosystem/1100bf14dc9c3b9af3e889e7276538e8 to your computer and use it in GitHub Desktop.
A Javascript function to flatten the provided array elements into a single array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function flatten(input) { | |
return input.reduce((acc, current) => { | |
return acc.concat(Array.isArray(current) ? flatten(current) : current) | |
}, []) | |
} | |
/** | |
* Tests | |
**/ | |
import flatten from "./flatten" | |
describe("flatten", () => { | |
const assertions = [ | |
{ value: [], expected: [] }, | |
{ | |
value: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], | |
expected: [1, 2, 3, 4, 5, 6, 7, 8, 9] | |
}, | |
{ value: [[1, 2, [3]], 4], expected: [1, 2, 3, 4] }, | |
{ value: [[1], [2], [3], [4]], expected: [1, 2, 3, 4] }, | |
{ | |
value: [[[[1]], 2, [3]], [4], [5, [6, [7, [[8]]]]]], | |
expected: [1, 2, 3, 4, 5, 6, 7, 8] | |
} | |
] | |
it("works with deeply nested arrays", () => { | |
assertions.forEach(({ value, expected }) => { | |
expect(flatten(value)).toEqual(expected) | |
}) | |
}) | |
it("works with falsy values", () => { | |
expect(flatten([null, [undefined], [0], [100]])).toEqual([ | |
null, | |
undefined, | |
0, | |
100 | |
]) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment