Created
October 15, 2018 20:15
-
-
Save richardvanbergen/611c82924fe230c4ad995453f728deb9 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
export function flatten(inputArr) { | |
return inputArr.reduce((outputArr, input) => { | |
if (Array.isArray(input)) { | |
return outputArr.concat(flatten(input)) | |
} | |
outputArr.push(input) | |
return outputArr | |
}, []) | |
} |
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
import { flatten } from './flatten' | |
test('it can flatten two dimentional arrays', () => { | |
expect(flatten([[1],[2]])).toEqual([1,2]) | |
}) | |
test('it can flatten more than two dimentions', () => { | |
expect(flatten([1,2,[3,4],[[5,6],[7]],[8]])).toEqual([1,2,3,4,5,6,7,8]) | |
}) | |
test('it can flatten mixed value types', () => { | |
expect(flatten(['1',2,[3,{}],[[5,6],[[]]],[.5]])).toEqual(['1',2,3,{},5,6,.5]) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi Richard,
your code looks good, thanks for your submission.
Just one question: what happens if I pass something that's not an array to the
flatten
function?Could you refactor it so that it throws an error?
Thanks
Stefano