As a newbie coder I’d be grateful for some feedback on how my code could be improved.
It’s my answer to the question below, taken from “The JavaScript Way” chapter 3 (available for free https://github.com/thejsway/thejsway) The only tools we’ve been given to solve this are the basics; variables, conditions, math operators.
Question -
Following second
Write a program that asks for a time under the form of three information (hours, minutes, seconds).
The program calculates and shows the time one second after. Incorrect inputs must
be taken into account.
This is not as simple as it seems… Look at the following results to see for yourself:
• 14h17m59s ⇒ 14h18m0s
• 6h59m59s ⇒ 7h0m0s
• 23h59m59s ⇒ 0h0m0s (midnight)
let hour = Number(prompt("what hour is it?"));
let minute = Number(prompt("what minute is it?"));
let second = Number(prompt("what second is it?"));
if (second > 59 || second < 0 || minute > 59 || minute < 0 || hour > 23 || hour < 0)
{
console.log("please, enter a valid time");
} else if ((hour === 23) && (minute === 59) && (second === 59)) {
hour = 0;
minute = 0;
second = 0;
console.log(`${hour}h ${minute}m ${second}s`);
} else if ((second <= 59) && (minute <= 59) && (hour <= 23)) {
hour++;
minute =0;
second =0;
console.log(`${hour}h ${minute}m ${second}s`);
} else if (second < 59 && hour <= 23 && minute <= 59) {
second++;
console.log(`${hour}h ${minute}m ${second}s`);
}
else if (second <= 59) {
second = 0;
minute++;
console.log(`${hour}h ${minute}m ${second}s`);
}