Created
July 3, 2019 12:39
-
-
Save Powell-v2/3a9ac336be5457b433791f746dbaddb8 to your computer and use it in GitHub Desktop.
Flatten array without using native `flat()`.
This file contains hidden or 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
`use strict` | |
const { isArray } = Array | |
const deepFlatten = (array) => { | |
if (!isArray(array)) { | |
throw new Error(`Expecting array to process, instead got ${typeof array}.`) | |
} | |
return array.reduce((accumulator, element) => | |
[ | |
...accumulator, | |
...(isArray(element) ? deepFlatten(element) : [element]) | |
], []) | |
} | |
module.exports = deepFlatten |
This file contains hidden or 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
`use strict` | |
const deepFlatten = require('./deepFlatten') | |
describe(`Array Deep Flatten`, () => { | |
it(`should throw if argument isn't array`, () => { | |
expect(() => deepFlatten(null)).toThrow() | |
expect(() => deepFlatten(0)).toThrow() | |
expect(() => deepFlatten(`zzz`)).toThrow() | |
expect(() => deepFlatten(new Set())).toThrow() | |
}) | |
it(`should return empty and shallow arrays as is`, () => { | |
expect(deepFlatten([])).toEqual([]) | |
expect(deepFlatten([1, 2, 3])).toEqual([1, 2, 3]) | |
}) | |
it(`should handle 2-level deep nesting`, () => { | |
expect(deepFlatten([[1, [2]], 3])).toEqual([1, 2, 3]) | |
}) | |
it(`should handle 4-level deep nesting`, () => { | |
expect(deepFlatten([[1, [2, [{}, [4]]]], 5])) | |
.toEqual([1, 2, {}, 4, 5]) | |
}) | |
it(`should handle 8-level deep nesting`, () => { | |
expect(deepFlatten([[1, [2, [3, [4, 5, 6, [7, [`8`, [null, []]]]]]]], 10])) | |
.toEqual([1, 2, 3, 4, 5, 6, 7, `8`, null, 10]) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment