Guest User

Untitled

a guest
Oct 17th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. //loop through the array
  2. //return the last item i===numbers.length-1
  3.  
  4. function max(numbers) {
  5. let maxVar = numbers[0];
  6. for(let i = 0, i < numbers.length, i++) {
  7. if (numbers[i] > maxVar) {
  8. maxVar = numbers[i];
  9. }
  10. }
  11. return maxVar;
  12. }
  13.  
  14.  
  15. function min(numbers) {
  16. let minVar = numbers[0];
  17. for(let i = 0, i < numbers.length, i++) {
  18. if (numbers[i] < minVar) {
  19. minVar = numbers[i];
  20. }
  21. }
  22. return minVar;
  23. }
  24.  
  25.  
  26. /*I had some ideas for how to solve this but they were way off. Even after looking at the answer it still doesn't work. THe idea makes perfect sense after seeing it. But I still can't make it work
  27.  
  28.  
  29.  
  30. /* From here down, you are not expected to
  31. understand.... for now :)
  32.  
  33.  
  34. Nothing to see here!
  35.  
  36. */
  37.  
  38. // tests
  39.  
  40. function testFunctionWorks(fn, input, expected) {
  41. if (fn(input) === expected) {
  42. console.log('SUCCESS: `' + fn.name + '` works on `[' + input + ']`');
  43. return true;
  44. } else {
  45. console.log(
  46. 'FAILURE: `' +
  47. fn.name +
  48. '([' +
  49. input +
  50. '])` should be ' +
  51. expected +
  52. ' but was ' +
  53. fn(input)
  54. );
  55. return false;
  56. }
  57. }
  58.  
  59. function testEmpty(fn) {
  60. if (fn([]) === null || fn([]) == undefined) {
  61. console.log(`SUCCESS: ${fn.name} works on empty arrays`);
  62. return true;
  63. } else {
  64. console.log(
  65. `FAILURE: ${fn.name} should return undefined or null for empty arrays`
  66. );
  67. return false;
  68. }
  69. }
  70.  
  71. (function runTests() {
  72. // we'll use the variables in our test cases
  73. const numList1 = [-5, 28, 98, -20013, 0.7878, 22, 115];
  74. const realMin1 = numList1[3];
  75. const realMax1 = numList1[6];
  76. const numList2 = [0, 1, 2, 3, 4];
  77. const realMin2 = numList2[0];
  78. const realMax2 = numList2[4];
  79.  
  80. const testResults = [
  81. testFunctionWorks(max, numList1, realMax1),
  82. testFunctionWorks(max, numList2, realMax2),
  83. testFunctionWorks(min, numList1, realMin1),
  84. testFunctionWorks(min, numList2, realMin2),
  85. testEmpty(max),
  86. testEmpty(min),
  87. ];
  88.  
  89. const numPassing = testResults.filter(function(result) {
  90. return result;
  91. }).length;
  92. console.log(numPassing + ' out of ' + testResults.length + ' tests passing.');
  93. })();
Add Comment
Please, Sign In to add comment