Advertisement
Guest User

Untitled

a guest
May 20th, 2019
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. const expect = require('chai').expect;
  2.  
  3. // Implementation of flatten(array)
  4. function flatten(array) {
  5. // early return if it is not an array or if empty
  6. if (!array || !Array.isArray(array)) {
  7. return;
  8. }
  9. return array.reduce((flattened, element) => {
  10. return flattened.concat(Array.isArray(element) ? flatten(element) : [element]);
  11. }, []);
  12. }
  13.  
  14. // Unit tests to run with Mocha and Chai.
  15. // In order to install, run
  16. // "npm install --save-dev mocha chai"
  17. // and then run "node_modules/.bin/mocha flatten.js"
  18. describe('flatten(array)', () => {
  19.  
  20. const assertResult = (input, output) => expect(flatten(input)).to.deep.equals(output);
  21.  
  22. it('should return undefined if the argument is not an array', () => {
  23. assertResult(undefined, undefined);
  24. assertResult({}, undefined);
  25. assertResult(1, undefined);
  26. assertResult("1", undefined);
  27. assertResult(true, undefined);
  28. });
  29.  
  30. it('should return an empty array if the argument is an empty array', () => {
  31. assertResult([], []);
  32. });
  33.  
  34. it('should return the same array if it is already flattened', () => {
  35. let input = [1, 2, 3];
  36. assertResult(input, input);
  37. });
  38.  
  39. it('should return a flattened array if it has one array in it', () => {
  40. let input = [1, [1, 2, 3], 4];
  41. let output = [1, 1, 2, 3, 4];
  42. assertResult(input, output);
  43. });
  44.  
  45. it('should return a flattened array for 3 nested levels', () => {
  46. let input = [1, [1, [2, [3]]], 4];
  47. let output = [1, 1, 2, 3, 4];
  48. assertResult(input, output);
  49. });
  50.  
  51. it('should return a flattened array for 99 nested levels', () => {
  52. let output = Array.from({ length: 99 }, (v, index) => index);
  53. // here we do not use the output of reduce, because each callback will be returning a reference to the last "nested"
  54. // array. So maintain the reference from the inital state
  55. let input = [];
  56. output.reduce((accum, element) => {
  57. let lastElementArray = [element];
  58. accum.push(lastElementArray);
  59. return lastElementArray;
  60. }, input);
  61. assertResult(input, output);
  62. });
  63. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement