Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
- ])
- })
- })
Add Comment
Please, Sign In to add comment