Advertisement
Guest User

Untitled

a guest
Sep 19th, 2019
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. export function flatten(input) {
  2. let output = [];
  3.  
  4. input.forEach((item) => {
  5. if (Array.isArray(item)) {
  6. output = output.concat(flatten(item));
  7. } else {
  8. output = output.concat([item]);
  9. }
  10. });
  11.  
  12. return output;
  13. }
  14.  
  15. describe('Array flatten', () => {
  16. it('should flatten an array no matter the type and/or depth of the entries', () => {
  17. expect(flatten([1, 2, 3, 4])).toEqual([1, 2, 3, 4]);
  18. expect(flatten([1, 2, [3], 4])).toEqual([1, 2, 3, 4]);
  19. expect(flatten([1, 2, [3], [4, 5, 6]])).toEqual([1, 2, 3, 4, 5, 6]);
  20. expect(flatten([1, 2, [3], [4, [5, 6, [7, 8, [9]]], 10]])).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
  21. expect(flatten([1, 2, [3, 'str'], { prop: 'value' }])).toEqual([1, 2, 3, 'str', { prop: 'value' }]);
  22. });
  23. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement