Have the function TimeConvert(num) take the num parameter being passed and return the number of hours and minutes the parameter converts to (ie. if num = 63 then the output should be 1:3). Separate the number of hours and minutes with a colon. Another example if input:126 then output: 2:06. This is what I did and I do not understand why it is wrong. For an input of 126, it is giving me an output of 11:06.
function TimeConvert(num) {
if(num<60 && num>10){
return 0+":"+num
}
if(num<10){
return 0+":"+0+num
}
let object={
12:720,
11:660,
10:600,
9:540,
8:480,
7:420,
6:360,
5:300,
4:240,
3:180,
2:120,
1:60
}
let time=""
for (let key in object){
while(num>=object[key]){
time += key
num-= object[key]
}
}
return time+":"+num
}
As noted in comments, there are many ways to reduce minutes to hours and minutes. However, to address your question as to why your approach is failing:
Object keys are treated as strings, not numbers. Also, you have declared time as a string.
For your approach to work, you have to make BOTH these changes:
let time="" -> let time = 0
and
time += key -> time += parseInt(key)
Working snippet:
console.log(TimeConvert(126));
function TimeConvert(num) {
if(num<60 && num>10){
return 0+":"+num
}
if(num<10){
return 0+":"+0+num
}
let object={
12:720,
11:660,
10:600,
9:540,
8:480,
7:420,
6:360,
5:300,
4:240,
3:180,
2:120,
1:60
}
let time=0;
for (let key in object){
while(num>=object[key]){
time += parseInt(key)
num-= object[key]
}
}
if (num<10) { num = "0"+num;} // add leading 0 and coerce to string if num <10;
return time+":"+num
}
Why not use this algorithm
const getHoursAndMinsString = (num) => {
if (num <= 0) {
return `0:00`
}
const hours = Math.floor(num / 60)
const mins = num % 60
return `${hours}:${mins.toString().padStart(2, "0")}`
}
Your object lookup is just encoding n=>n*60, but only for a subset of possible values so is arbitrarily limiting the range of values your function can operate on.
Removing that, and using floor and % to compute the hours and minutes respectively reduces the code down to:
function TimeConvert(num) {
let time = Math.floor(num / 60);
num = num % 60;
if (num < 10) { num = "0" + num; } // add leading 0 and coerce to string if num <10;
return time + ":" + num;
}
These calculations can also be done inline if you rather which reduces the code even further:
function TimeConvert(num) {
return Math.floor(num / 60) + ":" + ((num % 60) < 10 ? "0" : "") + (num % 60);
}
just watch out for negative values, or anything higher than 1440, which would overflow past 24 hours and you may want to start displaying with days.