shyan

Untitled

Jun 9th, 2021
517
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const oneSecond = () => 1000;
  2. const getCurrentTime = () => new Date();
  3. const clear = () => console.clear();
  4. const log = (message) => console.log(message);
  5.  
  6. //
  7. const compose =
  8.   (...fns) =>
  9.   (args) =>
  10.     fns.reduce((composed, f) => f(composed), args);
  11.  
  12. // Take a date object and return an object for clock time that contains hours, minutes, and seconds.
  13. const serializeClockTime = (date) => ({
  14.   hours: date.getHours(),
  15.   minutes: date.getMinutes(),
  16.   seconds: date.getSeconds(),
  17. });
  18.  
  19. //
  20. const civilianHours = (clockTime) => ({
  21.   ...clockTime,
  22.   hours: clockTime.hours > 12 ? clockTime.hours - 12 : clockTime.hours,
  23. });
  24.  
  25. const appendAMPM = (clockTime) => ({
  26.   ...clockTime,
  27.   ampm: clockTime.hours > 12 ? "PM" : "AM",
  28. });
  29.  
  30. // Take a target function and returns a function that will send a time to the target.
  31. const display = (target) => (time) => target(time);
  32.  
  33. // Take a template string and uses it to return clock time formatted based on the
  34. // criteria from the string.
  35. const formatClock = (format) => (time) =>
  36.   format
  37.     .replace("hh", time.hours)
  38.     .replace("mm", time.minutes)
  39.     .replace("ss", time.seconds)
  40.     .replace("tt", time.ampm);
  41.  
  42. // Take an object's key as an argument and prepends a zero to the value stored
  43. // under that object's key.
  44. const prependZero = (key) => (clockTime) => ({
  45.   ...clockTime,
  46.   key: clockTime[key] < 10 ? "0" + clockTime[key] : clockTime[key],
  47. });
  48.  
  49. // Takes clock time as an argument and transform it into civilian time
  50. const convertToCivilianTime = (clockTime) =>
  51.   compose(appendAMPM, civilianHours)(clockTime);
  52.  
  53. // Takes civilian clock time and make sure the hours, minutes, and seconds
  54. // display double digits by prepending zeros where needed.
  55. const doubleDigits = (civilianTime) =>
  56.   compose(
  57.     prependZero("hours"),
  58.     prependZero("minutes"),
  59.     prependZero("seconds")
  60.   )(civilianTime);
  61.  
  62. // Starts the clock by setting an interval that invokes a callback every second
  63. const startTicking = () =>
  64.   setInterval(
  65.     compose(
  66.       clear,
  67.       getCurrentTime,
  68.       serializeClockTime,
  69.       convertToCivilianTime,
  70.       doubleDigits,
  71.       formatClock("hh:mm:ss tt"),
  72.       display(log)
  73.     ),
  74.     oneSecond()
  75.   );
  76.  
  77. startTicking();
  78.  
RAW Paste Data