Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. const assert = require("assert");
  2.  
  3. /**
  4. * Write some code, that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4].
  5. */
  6.  
  7. function flattenArray(array) {
  8. if (!Array.isArray(array)) {
  9. throw new Error("Array expected");
  10. }
  11.  
  12. return array.reduce(
  13. (accumulator, element) =>
  14. accumulator.concat(Array.isArray(element) ? flattenArray(element) : element),
  15. []
  16. );
  17. }
  18.  
  19. assert.deepStrictEqual(flattenArray([[1,2,[3]],4]), [1,2,3,4], "Should flatten any nested array");
  20. assert.deepStrictEqual(flattenArray([1,2,3,4]), [1,2,3,4], "Should not flatten if not needed");
  21. assert.deepStrictEqual(flattenArray([]), [], "Should flatten empty array");
  22. assert.deepStrictEqual(flattenArray([[]]), [], "Should flatten nested empty arrays");
  23.  
  24. const errorValues = [
  25. null, undefined, {}, 1, "string", Date()
  26. ]
  27. errorValues.forEach(errorValue => {
  28. assert.throws(() => flattenArray(errorValue), 'Should throw an error when not an array is provided')
  29. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement