Skip to content

Instantly share code, notes, and snippets.

@asierba
Created May 21, 2018 11:12
Show Gist options
  • Save asierba/c2d1edf2c5f684c132b67331be8c157d to your computer and use it in GitHub Desktop.
Save asierba/c2d1edf2c5f684c132b67331be8c157d to your computer and use it in GitHub Desktop.
function that flattens an array in javascript
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