Skip to content

Instantly share code, notes, and snippets.

@israelalagbe
Created August 7, 2022 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save israelalagbe/12f3bd19a3145ba1a89e04a9349757b2 to your computer and use it in GitHub Desktop.
Save israelalagbe/12f3bd19a3145ba1a89e04a9349757b2 to your computer and use it in GitHub Desktop.
Time Units Converter
// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');
const MINUTE = 60
const HOUR = MINUTE * 60
const DAY = HOUR * 24
const WEEK = DAY * 7
function solution(time) {
const result = calculate(time)
if(result===""){
return "0s"
}
return result;
}
function calculate(time) {
if(time <= 1) {
return "";
}
else if(time < MINUTE) {
return `${time}s`
}
else if(time < HOUR) {
const seconds = time % MINUTE;
const minutes = Math.floor(time/MINUTE);
return `${minutes}m${calculate(seconds)}`;
}
else if(time < DAY) {
const seconds = time % HOUR;
const hours = Math.floor(time/HOUR);
return `${hours}h${calculate(seconds)}`;
}
else if(time < WEEK) {
const seconds = time % DAY;
const days = Math.floor(time/DAY);
return `${days}d${calculate(seconds)}`;
}
else {
const seconds = time % WEEK;
const weeks = Math.floor(time/WEEK);
return `${weeks}w${calculate(seconds)}`;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment