Created
November 26, 2019 16:18
-
-
Save diogobeda/77f9351923011bb3b1083e0e09cecd67 to your computer and use it in GitHub Desktop.
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
const flatten = (input) => input.reduce((acc, item) => { | |
const flattenedItem = item instanceof Array | |
? flatten(item) | |
: item; | |
return acc.concat(flattenedItem); | |
}, []); |
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
describe('flatten', () => { | |
describe('when array input is not nested', () => { | |
it('should return original array', () => { | |
const actual = flatten([1,2,3,4]); | |
const expected = [1,2,3,4]; | |
expect(actual).toEqual(expected); | |
}); | |
}); | |
describe('when array input is one-level nested', () => { | |
it('should return flattened array', () => { | |
const actual = flatten([1,2,3,[4]]); | |
const expected = [1,2,3,4]; | |
expect(actual).toEqual(expected); | |
}); | |
}); | |
describe('when array input is more than one-level nested', () => { | |
it('should return flattened array', () => { | |
const actual = flatten([[[0]], 1,2,[3],[4, [5]]]); | |
const expected = [1,2,3,4,5]; | |
expect(actual).toEqual(expected); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment