Guest User

Untitled

a guest
Oct 20th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. let testCases = [
  2. [[1,2,3,4,4,5,1,4,2], 3],
  3. [[3,4,4,2], 2],
  4. [[,2,3,4,1], 1],
  5. [[9,1,2], 2],
  6. [[], 0],
  7. [[undefined, undefined], 0],
  8. [null, 0],
  9. ];
  10.  
  11. //
  12. testCases.forEach(testRunner(build));
  13. //
  14.  
  15. function build(terrain) {
  16. terrain = terrain || [];
  17. let castleCount = terrain.reduce(([castleCount, sidecar], current) => {
  18. switch (sidecar.length) {
  19. case 0: {
  20. return [castleCount, [current]];
  21. };
  22.  
  23. case 1: {
  24. let [lastEntry] = sidecar;
  25. return lastEntry == current
  26. ? [castleCount, sidecar]
  27. : [castleCount, [...sidecar, current]];
  28. };
  29.  
  30. case 2: {
  31. /**
  32. * [1 , 9]
  33. * [9, 1]
  34. */
  35. let [start, middle] = sidecar;
  36. let isValley = (middle < start) && (middle < current);
  37. let isPeak = (middle > start) && (middle > current);
  38. return (isPeak || isValley)
  39. ? [castleCount+1, [current]]
  40. : [castleCount, sidecar];
  41. }
  42. }
  43. }, [0, []])[0];
  44. return Boolean(terrain[0])
  45. ? castleCount+1
  46. : castleCount;
  47. }
  48.  
  49. function testRunner(testFunc) {
  50. return ([input, expectedOutput]) => {
  51. let actualOutput = build(input);
  52. if(actualOutput === expectedOutput) {
  53. console.log("Test passed.");
  54. } else {
  55. console.log("Test failed.")
  56. }
  57. console.log("input: ", input);
  58. console.log("expectedOutput: ", expectedOutput);
  59. console.log("actualOutput: ", actualOutput);
  60. console.log("===========");
  61. }
  62. }
Add Comment
Please, Sign In to add comment