Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. // 'flatten' flattend arbitrary nested value sequences into
  2. // a single array of values
  3. const flatten = (input: []): number[] => {
  4.  
  5. const flattened: number[] = []
  6.  
  7. for (let i = 0; i < input.length; i++) {
  8. // If current value is an array, call flatten on it too
  9. if (Array.isArray(input[i])) {
  10. // flatten returned array with spread operator
  11. flattened.push(...flatten(input[i]))
  12. } else {
  13. // If value is a primitive, push it into answer array
  14. flattened.push(input[i])
  15. }
  16. }
  17.  
  18. return flattened
  19. }
  20.  
  21. module.exports = flatten
  22.  
  23. //// Tests
  24. //// Since you guys asked for a single file, I've added the commented tests below :)
  25. /*
  26. const flatten = require('./flatten.ts')
  27.  
  28. describe('flatten', () => {
  29.  
  30. expect(flatten([
  31. [1, 2, [3]], a
  32. 4
  33. ])).toEqual([
  34. 1, 2, 3, 4
  35. ])
  36.  
  37. expect(flatten([
  38. [1, [2, [3]]],
  39. [[4]]
  40. ])).toEqual([
  41. 1, 2, 3, 4
  42. ])
  43.  
  44. expect(flatten([
  45. [[[[[[[[1]]]]]]], 2],
  46. [[3], [[[[[[4]]]]]]], 5
  47. ])).toEqual([
  48. 1, 2, 3, 4, 5
  49. ])
  50.  
  51. })
  52. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement