Skip to content

Instantly share code, notes, and snippets.

@Powell-v2
Created July 3, 2019 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Powell-v2/3a9ac336be5457b433791f746dbaddb8 to your computer and use it in GitHub Desktop.
Save Powell-v2/3a9ac336be5457b433791f746dbaddb8 to your computer and use it in GitHub Desktop.
Flatten array without using native `flat()`.
`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
`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