Created
March 16, 2019 12:26
-
-
Save philcms1/2af5001fb598a4151647d1847db5e3b9 to your computer and use it in GitHub Desktop.
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
const flattenArr = (arr = []) => { | |
// Executing recursively a reducer function seems the logical choice, since it will result... | |
// ...in a single output value | |
return arr.reduce((accumulator, currentValue) => { | |
return accumulator.concat(Array.isArray(currentValue) ? flattenArr(currentValue) : currentValue); | |
}, []); | |
}; | |
// Using Jest for testing | |
test('[[1,2,[3]],4] -> [1,2,3,4]', () => { | |
expect(flattenArr([[1,2,[3]],4])).toEqual([1,2,3,4]); | |
}); | |
test('[] -> []', () => { | |
expect(flattenArr([])).toEqual([]); | |
}); | |
test('undefined -> []]', () => { | |
expect(flattenArr()).toEqual([]); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment