Skip to content

Instantly share code, notes, and snippets.

@li-helen
Created July 2, 2019 20:55
Show Gist options
  • Select an option

  • Save li-helen/c875e299b530ea70c2735e91e735ef7c to your computer and use it in GitHub Desktop.

Select an option

Save li-helen/c875e299b530ea70c2735e91e735ef7c to your computer and use it in GitHub Desktop.

Clock Minute Adder

REPL

Helpful Modulo Explanation

Instructions

Given:

  • A "base" time in string format 'HH:MM'
  • A number of minutes

Create a function that:

  • Adds the number of minutes to the "base" time
  • Returns the resulting time in 'HH:MM' format

Remember:

  • You're working with a standard 12-hour clock
  • Hours are one-indexed, not zero-indexed (e.g. there is no 0:40, it's 12:40)

Example Output

addMinutes('01:30', 30);     // 2:00
addMinutes('12:30', 40);     // 1:10
addMinutes('11:59', 1);      // 12:00
addMinutes('01:59', 240);    // 5:59
addMinutes('01:23', 456789); // 6:32

Solution and Explanation

One valid solution handles hours and minutes separately, and makes use of modular math:

To get total minutes we add the base minute value to the given minutes to add. From there, if we mod (%) by 60 we'll get the remainder, which tells us where the minute hand would end up.

For hours, we already have the total number of minutes, so we can get the total number of hours by dividing that by 60, then the final number of hours by modding (%) by 12.

EDGE CASE: The hours are "one-indexed" not "zero-indexed", i.e. there's no such time as 0:40 (well for non-military clocks), instead it's 12:40. To solve this, we can subtract 1 then mod by 12 then add 1.


Solution Code

function addMinutes (baseTime, minutesToAdd) {
  // turn the base time string into an array of 2 numbers
  const [baseHours, baseMinutes] = baseTime.split(':').map(str => Number(str));

  // convert base time to only minutes & get total minutes
  const baseTotalMinutes = (baseHours * 60) + baseMinutes;
  const newTotalMinutes = baseTotalMinutes + minutesToAdd;

  // Using new total minutes, calculate the hours by dividing by 60
  const totalHours = Math.floor(newTotalMinutes / 60);

  // This takes care of accounting for a 12 hour clock
  // Why do we need to subtract and add 1 here?
  const newHours = ((totalHours - 1) % 12) + 1;
  
  // Find minutes by determining how many are left over after dividing by 60
  const newMinutes = newTotalMinutes % 60;
  
  // Create return string (account for extra 0 for minutes under 10)
  return `${newHours}:${newMinutes > 9 ? newMinutes : `0${newMinutes}`}`;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment