Skip to content

Instantly share code, notes, and snippets.

@diogobeda
Created November 26, 2019 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diogobeda/77f9351923011bb3b1083e0e09cecd67 to your computer and use it in GitHub Desktop.
Save diogobeda/77f9351923011bb3b1083e0e09cecd67 to your computer and use it in GitHub Desktop.
const flatten = (input) => input.reduce((acc, item) => {
const flattenedItem = item instanceof Array
? flatten(item)
: item;
return acc.concat(flattenedItem);
}, []);
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