Advertisement
CLooker

Untitled

Feb 9th, 2018
407
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // https://www.hackerrank.com/challenges/breaking-best-and-worst-records/problem
  2.  
  3. // choose your weapon
  4.  
  5. // declarative, implicit return, nested ternary confusing to some
  6. const breakingRecords = scores =>
  7.   scores.reduce(
  8.     ({ high, low, answer }, s, index) =>
  9.       s > high
  10.         ? { low, high: s, answer: [++answer[0], answer[1]] }
  11.         : s < low
  12.           ? { low: s, high, answer: [answer[0], ++answer[1]] }
  13.           : { low, high, answer },
  14.     {
  15.       high: scores[0],
  16.       low: scores[0],
  17.       answer: [0, 0]
  18.     }
  19.   ).answer;
  20.  
  21. // possibly more readable
  22. const breakingRecords = scores =>
  23.   scores.reduce(
  24.     ({ high, low, answer }, s, index) => {
  25.       s > high && ((high = s), ++answer[0]);
  26.       s < low && ((low = s), ++answer[1]);
  27.       return { low, high, answer };
  28.     },
  29.     {
  30.       high: scores[0],
  31.       low: scores[0],
  32.       answer: [0, 0]
  33.     }
  34.   ).answer;
  35.  
  36. // return statements short-circuit to minimze unnecessary operations
  37. const breakingRecords = scores =>
  38.   scores.reduce(
  39.     ({ high, low, answer }, s, index) => {
  40.       if (s > high) {
  41.         return { low, high: s, answer: [++answer[0], answer[1]] };
  42.       }
  43.       if (s < low) {
  44.         return { low: s, high, answer: [answer[0], ++answer[1]] };
  45.       }
  46.       return { low, high, answer };
  47.     },
  48.     {
  49.       high: scores[0],
  50.       low: scores[0],
  51.       answer: [0, 0]
  52.     }
  53.   ).answer;
  54.  
  55. // imperative
  56. function breakingRecords(scores) {
  57.   let high = scores[0];
  58.   let low = scores[0];
  59.   let answer = [0, 0];
  60.   for (let i = 1; i < scores.length; i++) {
  61.     if (scores[i] > high) {
  62.       high = scores[i];
  63.       ++answer[0];
  64.     }
  65.     if (scores[i] < low) {
  66.       low = scores[i];
  67.       ++answer[1];
  68.     }
  69.   }
  70.   return answer;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement