Created
May 21, 2018 11:12
-
-
Save asierba/c2d1edf2c5f684c132b67331be8c157d to your computer and use it in GitHub Desktop.
function that flattens an array in javascript
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
function flatten(items) { | |
return items.reduce((result, current) => { | |
if (current.constructor === Array) | |
return result.concat(flatten(current)) | |
return result.concat(current); | |
}, []); | |
} | |
describe('flatten', () => { | |
it('should ignore array with no elements', () => { | |
expect(flatten([])).toEqual([]); | |
}); | |
it('should ignore array with no nested arrays', () => { | |
expect(flatten(['a','b','c'])).toEqual(['a','b','c']); | |
}); | |
it('should expand nested arrays', () => { | |
expect(flatten(['a',['b1','b2','b3'],'c'])).toEqual(['a','b1','b2','b3','c']); | |
expect(flatten([[1,2,[3]],4])).toEqual([1,2,3,4]); | |
}); | |
it('should expand multiple levels of nested arrays', () => { | |
expect(flatten(['a',['b1','b2',['b31','b32']],'c'])).toEqual(['a','b1','b2','b31','b32','c']); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment