Advertisement
Guest User

Untitled

a guest
Oct 16th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. describe("flatten an array of arbitrarily nested arrays of integers into a flat array of integers", function () {
  2. it("Should return empty array when given empty array provided", function () {
  3. expect(flatten([])).toEqual([]);
  4. });
  5.  
  6. it("Should return a flat array when given a flat array provided", function () {
  7. expect(flatten([1])).toEqual([1]);
  8. });
  9.  
  10. it("Should return an empty array when given undefined", function () {
  11. expect(flatten(undefined)).toEqual([]);
  12. });
  13.  
  14. it("Should return [1,2,3,4] on [[[1],2,3,4]] provided", function () {
  15. expect(flatten([[[1], 2, 3, 4]])).toEqual([1, 2, 3, 4]);
  16. });
  17.  
  18. it("Should return [1,2,3,4] on [[1,2,[3]],4] provided", function () {
  19. expect(flatten([[1, 2, [3]], 4])).toEqual([1, 2, 3, 4]);
  20. });
  21. it("Should return [1,2,3,4] on [[1,2,[3],4]] provided", function () {
  22. expect(flatten([[1, 2, [3], 4]])).toEqual([1, 2, 3, 4]);
  23. });
  24. });
  25.  
  26.  
  27. function flatten(arr) {
  28. if (!Array.isArray(arr)) return [];
  29. return arr.reduce(function (acc, x) {
  30. return acc.concat(Array.isArray(x) ? flatten(x) : [x]);
  31. }, []);
  32. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement