Guest User

Untitled

a guest
Nov 20th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  1. function flatten(input) {
  2. return input.reduce((acc, current) => {
  3. return acc.concat(Array.isArray(current) ? flatten(current) : current)
  4. }, [])
  5. }
  6.  
  7.  
  8. /**
  9. * Tests
  10. **/
  11. import flatten from "./flatten"
  12.  
  13. describe("flatten", () => {
  14. const assertions = [
  15. { value: [], expected: [] },
  16. {
  17. value: [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
  18. expected: [1, 2, 3, 4, 5, 6, 7, 8, 9]
  19. },
  20. { value: [[1, 2, [3]], 4], expected: [1, 2, 3, 4] },
  21. { value: [[1], [2], [3], [4]], expected: [1, 2, 3, 4] },
  22. {
  23. value: [[[[1]], 2, [3]], [4], [5, [6, [7, [[8]]]]]],
  24. expected: [1, 2, 3, 4, 5, 6, 7, 8]
  25. }
  26. ]
  27.  
  28. it("works with deeply nested arrays", () => {
  29. assertions.forEach(({ value, expected }) => {
  30. expect(flatten(value)).toEqual(expected)
  31. })
  32. })
  33.  
  34. it("works with falsy values", () => {
  35. expect(flatten([null, [undefined], [0], [100]])).toEqual([
  36. null,
  37. undefined,
  38. 0,
  39. 100
  40. ])
  41. })
  42. })
Add Comment
Please, Sign In to add comment