0

I'm trying to do a coding challenge on Coderbyte. I have to find the difference in minutes between two inputted times (eg: "12:00am-12:00pm"). This is my code:

function getMinutes(str) {
  var pattern = /(\d+)\:(\d+)([ap]m)/i;
  var matches = str.toString().match(pattern);
  **// return matches**
  if (matches == null) {
    return matches;
  }

  var hour = parseInt(matches[1]);
  var minutes = parseInt(matches[2]);
  var extra = (matches[3] == "am") ? 0 : 720;

  if (hour == 12)
    hour = 0;

  return (hour * 60) + minutes + extra;
}

function CountingMinutesI(str) { 
  var chunks = str.split("-");
  var minuteA = getMinutes(chunks[0]), minuteB = getMinutes(chunks[1]);
  return getMinutes(minuteA) + " " + getMinutes(minuteB);
}


// keep this function call here 
// to see how to enter arguments in JavaScript scroll down
CountingMinutesI(readline());

For some reason in getMinutes, matches is null even though it shouldn't be. If you uncomment the bolded line that says "return matches", then it will give me the valid array with all the matches. But if I comment that line out, then matches becomes null. Why? This is so strange.

3
  • 1
    what are you expecting? "0 720"? Commented Dec 18, 2014 at 3:14
  • Yes. But first I want to know why the matches array is valid at first, but then one line later it's null. Commented Dec 18, 2014 at 3:16
  • matches becomes null where? Step through your code with the debugger. Are you sure that you've cut and pasted your code properly, and that it doesn't say if (matches = null)? Commented Dec 18, 2014 at 3:16

2 Answers 2

3

There is simple oversight in CountingMinutesI(). You are going getMinutes twice. Replace

  return getMinutes(minuteA) + " " + getMinutes(minuteB);

With

  return minuteA + " " + minuteB;
Sign up to request clarification or add additional context in comments.

Comments

1

In the CountingMinutesI function, you are calling getMinutes() a total of 4 times, one for the first chunk, one for the second chunk, one with the result of the first call (0), and one with the result of the second call (720).

Those second two calls are the problem, they result in the function trying to match the regex against "0" and "720" respectively, neither of which will work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.