12 vs 24 hour clock
Learning Objectives
We usually write the time in one of two ways: the analogue 12 hour clock or the digital 24 hour clock. The 12 hour clock counts up to 12: it resets at midday. The 24 hour clock counts up to 24: it resets at midnight.
| 2️⃣4️⃣ hour time | 🕛 12 hour time |
|---|---|
| 09:00 | 09:00 am |
| 10:00 | 10:00 am |
| 11:30 | 11:30 am |
| 12:00 | 12:00 pm |
| 13:43 | 1:43 pm |
| 14:00 | 2:00 pm |
We use the notation “HH:MM”. HH is our stand-in for the hours value. MM is our stand-in for the minutes value.
🧩 Stating the problem
Let’s pose a problem: given any time in 24 hour clock, we want to format it as a 12 hour clock time. To achieve this goal, we’re going to implement a function formatAs12HourClock.
Given a time in 24 hour clock
When we call formatAs12HourClock
Then we get back a string representing the same time in 12 hour clock.
🧪 Our tests:
I expect formatAs12HourClock("09:00") to be "09:00 am"
I expect formatAs12HourClock("14:19") to be "2:19 pm"
Comparing current and target output
Learning Objectives
❗Caution
This block is currently in two places and both need to be updated:
In Onboarding: Rewrite as a general intro to comparing values. Trainees have not covered functions at this point
In Structuring & Testing Data: This would be a useful refresher before we start testing, but needs the context that trainees will already be familiar with teh concept
Let’s start with a function declaration of formatAs12HourClock:
function formatAs12HourClock() {}Whenever we call formatAs12HourClock we expect it to return a particular value, which we call the 🎯 target output. For example, we expect formatAs12HourClock("08:00") to return "08:00 am". "08:00 am" is the 🎯 target output.
However, the current output is what the function actually returns right now.
Let’s start with formatAs12HourClock defined like this:
function formatAs12HourClock() {}Suppose we now call the function like this:
formatAs12HourClock("05:30");💬 Correct! The target output should append ‘am’ to maintain the 12-hour clock format.
💬 Not quite - based on the examples, we use lowercase ‘am’.
💬 No - we want to preserve the leading zero.
💬 No - we want 12-hour format, not 24-hour format.
👉🏼 Keep going
Let’s continue with formatAs12HourClock defined like this:
function formatAs12HourClock() {}Suppose we call the function like this:
formatAs12HourClock("20:10");💬 Correct! Since the function is empty and has no return statement, it returns undefined by default.
💬 Not quite - remember that the function is currently empty with no implementation.
💬 No - an empty function returns undefined, not null.
💬 No - an empty function executes successfully but returns undefined.
🧩 Comparing values
We have learned how to log values to the console. We can also compare two values. We check that a function produces some target output with a comparison.
We compare the current output of formatAs12HourClock("08:00") with the target output of "08:00 am" and ask: are these two values the same? We use a comparison operator to compare two expressions and check if they evaluate to the same value. We use the strict equality operator === to check if two values are the same.
Left equals Right
formatAs12HourClock("08:00") === "8:00 am";=== checks if the values on the left and right of the operator are the same. We can think of formatAs12HourClock("08:00") === "8:00 am" as the question: “Is the return value of formatAs12HourClock("08:00") equal to "8:00 am" ?” This leads to the question:
What will the expression
formatAs12HourClock("08:00") === "8:00 am"evaluate to?
✅ ❌ Boolean values
Does 1 equal 0? Yes or No? True or False?
Some values are best represented as strings: any piece of text, a name, address, etc will most likely be stored using the string data type. The number data type can store numbers we use in calculations.
If we’re comparing two things, there are only two different states: true or false. This leads us to the boolean datatype, which only has true or false values. Whenever we compare two values with a comparison operator, we end up with a boolean value: true or false. It’s one or the other. It’s boolean.
// using the strict equality comparison expression
console.log(42 === 10 + 32);
// logs true
console.log(10 * 5 === 60);
// logs false
Look at the code below and predict what each expression will evaluate to. Write your prediction down. Use the Node REPL to check your answers. Check out some relevant documentation if you’ve not seen a particular operator before.
| |
👉🏿 Keep Going
Look at the code below and predict what each expression will evaluate to. Write your prediction down. Use the Node REPL to check your answers. Check out some relevant documentation if you’ve not seen a particular operator before
| |
👉🏿 Keep Going
Checking misconceptions 🤔
Look at the code below and then predict what the expression will evaluate to. Be sure to explain your answer too. Use the Node Repl to check your answer. Does the REPL output make sense?
Try using the Node Repl to check your answer. Does the REPL output make sense?
| |
Writing an assertion
Learning Objectives
We now have 2 new concepts: booleans and comparisons. From these concepts, we can now write an assertion about the function formatAs12HourClock.
🔑 An assertion is a check that our code behaves in a particular way: this check can either succeed or fail.
So far we’ve used the log function console.log. We can write assertions using another function: console.assert. The documentation says that console.assert writes an error message to the console if the assertion is false. If the assertion is true, nothing happens. As 10 + 32 === 42 evaluates to true, no message will be written to the console.
const calculation = 10 + 32;
const result = 42;
console.assert(calculation === result);Experiment with assertions
const calculation = 10 + 32;
const result = 42;
console.assert(calculation === result);Change the value assigned to the result variable to make the assertion fail. Check the output you get in the console.
👉🏿 Keep Going
Let’s look at an example using formatAs12HourClock:
function formatAs12HourClock() {}
console.assert(formatAs12HourClock("08:00") === "08:00 am");Predict and explain if the assertion will succeed or fail. Pay particular attention to the return value of formatAs12HourClock.
Clarity with arguments
It would be useful to have more information as to why this assertion failed. We can pass an additional argument to console.assert:
function formatAs12HourClock() {}
console.assert(
formatAs12HourClock("08:00") === "08:00 am",
`current output: ${formatAs12HourClock("08:00")}, target output: 08:00 am`
);Let’s break down these arguments to make sense of what’s going on:
- first argument -
formatAs12HourClock("08:00") === "08:00 am"- the condition we’re checking - second argument -
`current output: ${formatAs12HourClock("08:00")}, target output: 08:00 am`- a message string that will be logged to the console if the condition is false.
🧹 Refactor
We can tidy up the assertion even further. As we’re reusing the same expressions, we can store their result in variables with meaningful names so we can reuse them:
| |
Execute this code; we now get a log in the console:
Assertion failed: current output: undefined, target output: 08:00 am🧰 Implementing the functionality
On line 3, the function is being passed a single argument "08:00". But our function ignores it: it doesn’t declare any parameters. We can parameterise the function and label the input as time:
function formatAs12HourClock(time) {}According to our assertion, when we call our function with an input of "08:00" we need to create an output of "08:00 am". If we add "am" to the time, we’ll get the target output. We can update our function with a template literal, set the return value and then re-run our code including our assertion to check the function is returning the correct value.
📓 We can and should continually check our assertions to see if our function’s current output meets our target output.
| |
✅ Nothing is printed to the console, so this assertion is passing 😎
🕹️Try yourself
💼 Checking different cases
So far we’ve only created assertions that check the function’s behaviour for times between midnight and midday. In these cases, there is a pattern: take the current time and add " am" to the end.
But this isn’t the pattern we need to follow for all times. To make sure our function works for all times, we need to write more assertions.
We need to assert that the function behaves correctly when the time is later than midday.
Before we think about any code, we should think about our problem. Separating problem and code lets us focus better. First we can focus on the data. Then we can focus on the code.
First, let’s think of an example time in 24 hour clock - we’ll pick 23:00.
Next, let’s work out what we expect our example time to be in 12 hour clock: 11:00 pm.
Now that we’ve thought about the problem, we can write the code. Let’s create an assertion for our function when passed an input of "23:00":
| |
Save this code to a file. Before you run it in Node, write down what you think will happen. Then run it with Node - compare what you saw with what you predicted.
Forming sub-goals
Learning Objectives
For formatAs12HourClock our strategy for inputs like "23:00" involves checking if the hours value is less than 12. For this purpose, we can use the greater than comparison operator >.
> will check if the value on the operator’s left side is less than the value on the operator’s right side.
So 3 > 12 evaluates to false, as 3 is not greater than 12.
So provided we have an expression for hours, we can write an if statement as follows:
if (/* here goes an expression here that evaluates to the hours */ < 12) {
// do code to format the 12 hours
}To complete the logic, we can form a
Any time we’re solving a problem, we can define a goal - a thing we need to achieve to consider the problem solved. We can break a problem into smaller problems, each with its own sub-goal. The problem-solving process involves continually breaking down problems into smaller manageable problems, each with its own sub-goal.
For the implementation of formatAs12HourClock, we can form a sub-goal as follows:
🎯 Sub-goal: Find the hours value from the
timeinput
Accessing strings
Learning Objectives
Given a time string we need to access the first 2 characters of the string which represent the hours.
Strings are zero-indexed.
Index means position, so zero-indexed means we start counting character positions from 0 onwards.
Here are the positions/indexes for "23:00"
| index | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| character | "2" | "3" | ":" | "0" | "0" |
In JavaScript, we can use square bracket notation to access specific characters in the string using the index.
time[0]; // evaluates to "2"
time[1]; // evaluates to "3"
time[2]; // evaluates to ":"
// etc
Square bracket access will only give a single character. We must use another method to extract multiple characters from the given string.
✂️ Extracting a slice
To extract 1 or more characters from a string, we can use a function called
slice is a function that can take 2 arguments: a start index and an end index. slice will return a section of the string from the start index up to but not including the end index.
time; // holds the value "23:00"
time.slice(0, 2); // will access the characters below
| index | 0 | 1 |
|---|---|---|
| character | "2" | "3" |
So time.slice(0,2) will evaluate to "23" when the time is "23:00".
Finally we must convert "23" to the number 23, otherwise we can’t compare this value properly.
✍️exercise
Think about the numbers 100 and 23. Which one is bigger?
Write code which compares the strings "100" and "23" and tells you which one is bigger.
Does this match your expectation? If not, what do you think is happening?
JavaScript uses different ways to compare values depending on their types. If you compare two strings (which may contain numbers), it will do something different than if you compare two numbers.
We can use the Number function to convert the string into a number.
✍️exercise
Work out how you can convert the strings “100” and “23” to numbers.
Write code which compares the numbers 100 and 23 and tells you which one is bigger.
Testing a sub-goal
Learning Objectives
Earlier we defined a sub-goal to find a value for the hours from the time input. We’ve found that Number(time.slice(0,2)) is an expression that evaluates to the hours from time. So we can write an if statement using this expression:
if (Number(time.slice(0, 2)) > 12) {
}If the time is "23:00" then the expression Number(time.slice(0, 2)) > 12 will evaluate to true and the body of the if statement will be executed.
This if statement is implementing the following part of the diagram from earlier:
Before we worry about how we handle times in the afternoon, we can check that we’ve solved this sub-goal.
We can check that we are correctly identifying times in the afternoon by adding in our if statement (which we think is correct), with a placeholder body:
| |
If we run our code, we expect the current output of the 23:00 test-case to have changed. It won’t be correct - the assertion will still fail. But if it hasn’t changed, we know our if statement is wrong.
% node clock-example.js
Assertion failed: current output: Don't know how to handle times in the afternoon yet, target output: 11:00 pm
Even though we know the code on line 3 is incorrect, this was a useful step. It allowed us to run our code more often, and check that we’re on the right track.
remember
Run your code as often as you can.
Make small changes and run your code.
Sometimes we write code we know we will delete because it lets us get feedback sooner.
Now we can focus on just one problem: how to handle times after midday (i.e. fixing line 3). We don’t need to worry about both detecting the time and handling it.
If the output of this assert still printed "23:00 am" we would have stopped here and debugged that. Again, we could focus on just one problem.
Sub-goal #2
Learning Objectives
Now we can think about what we do when we’ve identified a time is after midday.
Earlier, we observed what to do when the time goes beyond midday: subtract 12 from the hours time to get the new hours for the 12 hour clock time.
Before writing code, we can define our approach in steps:
Starting with an input like "23:00":
Now we can format the string using our approach from earlier:
we’ll need to append "pm" to the string expression and subtract 12 from the hours. So we get the following:
if (Number(time.slice(0, 2)) > 12) {
return `${Number(time.slice(0, 2)) - 12}:00 pm`;
}The return statement above implements the following steps we set out earlier:
Now we can re-run our assertions from earlier to check our function behaves as target.
Refactoring repetition
Learning Objectives
Let’s look at our code, which passes all of the tests we’ve written:
| |
Inside the formatAs12HourClock function we do exactly the same thing twice.
🕹️Exercise
formatAs12HourClock that do exactly the same thing.There are a few reasons this isn’t ideal.
- It’s not clear what this value represents. You can read it and work it out, but that takes some time.
- Doing the same thing twice is slower than doing it once.
- In the future if we need to change this code’s implementation, we would need to change it twice.
Right now our code assumes the hours in a time are always two digits (like05:00). What if we wanted to support single-digit hours, like5:00? We would need to make the same change to both lines. It would be easy to change one line and forget the other, which would lead to a bug.
Refactor
Once your code passes your test, look for ways you could make your code better. This doesn’t mean changing what it does - the code works. It means changing how it’s written.
This is called
We can refactor our code to remove this duplication by introducing a variable:
| |
This code does exactly the same thing as the previous code. But it is better in a few ways:
- We can now tell more easily what this expression represents. The variable name conveys: it’s the hours from the time.
- We only compute the hours once, not twice, which will be a little bit faster.
- If we need to change how we identify the hours (e.g. to support single-digit hours), we only need to update one bit of code. Both lines 3 and 4 will automatically use the same value, because they’re referring to the same variable.
💡Code Quality
Whenever you finish implementing a sub-goal, or a goal, read your code and look for ways to refactor it.
This will make your code easier to continue working on.
Identifying missing tests
Learning Objectives
We started off writing one test for our code - checking that it correctly handled the input 08:00. We wrote an implementation that passed all our (1) tests!
Then we realised there was a bug - it didn’t handle times after midday correctly. So we wrote another test - for the input 23:00. We saw our implementation failed that test. And we fixed it. And we had an implementation that passed all our (2) tests!
When will we be happy that our implementation works for all possible inputs? When do we have enough tests?
Groups of input
One way to approach this is to think about what groups of input our problem may have.
We’ve already identified two examples of groups of input to the problem of converting 24 hour clocks to 12 hour clocks: Times before midday and times after midday.
One way to find extra cases to consider (and extra tests to write) is to try to think of different groups of input.
For example, some times are exactly on the hour (end in :00) and other times have a non-zero number of minutes.
✍️exercise
Set a timer for 5 minutes. Write down as many groups of input to this problem as you can. Write an example assertion for each one.
If you find any bugs in the implementation, go fix them!
Edge cases
Another way to consider this question is to think about what edge cases there are in the problem.
📖Definition: edge case
An edge case is an unusual value which may need special treatment.
Some examples are: the minimum value, the maximum value, and the boundary between two groups of input.
- Some example edge cases for this problem are:
00:00- The minimum time, which is
12:00 amin 12 hour clock.
This is also the only hour that is bigger in 12 hour clock than 24 hour clock. 24:00- The maximum time.
12:00- Where time changes from am to pm. The edge between morning times and afternoon times.
Often these edge cases are where bugs happen.
✍️exercise
Set a timer for 5 minutes. Write down as many edge cases of input to this problem as you can. Write an example assertion for each one.
If you find any bugs in the implementation, go fix them!