Advertisement
Guest User

Untitled

a guest
Mar 26th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. /**
  2. * Return the flattened version of an arbitrarily deep nested array as a new
  3. * array, keeping the original unchanged. It uses a simple recursive algorithm.
  4. *
  5. * Positives: clean, intuitive, doesn't mutate the argument
  6. * Negatives: 1) probably uses more memory than alternative implementations.
  7. * 2) recursive, so in theory more limited by system resources than
  8. * an alternative non-recursive algorithm would be. Unlikely to
  9. * be a problem in most use cases but if you had an array nested
  10. * say 1 million levels deep, probably wouldn't want to use this
  11. * method.
  12. *
  13. * @param unflattened
  14. */
  15.  
  16. export default function flatten(unflattened: any[]) {
  17. try {
  18. return unflattened.reduce(
  19. (flattened: any[], currElement: any) =>
  20. flattened.concat(
  21. Array.isArray(currElement) ? flatten(currElement) : currElement,
  22. ),
  23. [],
  24. );
  25. } catch (error) {
  26. // because Typescript !== foolproof
  27. return console.error(`Error! ${error.message}`);
  28. }
  29. }
  30.  
  31. function test(arg: any) {
  32. console.log(
  33. `flatten(${JSON.stringify(arg)}) = ${JSON.stringify(flatten(arg))}`,
  34. );
  35. }
  36.  
  37. export function tests() {
  38. test([1, [2, 3, [4, 5, 6, [[7], 8], 9, 10]]]);
  39. test([1, 2, 3, 4]);
  40. test(2);
  41. test(('hello' as any) as number[]);
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement