Skip to content

Instantly share code, notes, and snippets.

@hirenchauhan2
Last active September 26, 2017 07:02
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 hirenchauhan2/2db4bd52c0cdd7d001ca7077d17cf6d8 to your computer and use it in GitHub Desktop.
Save hirenchauhan2/2db4bd52c0cdd7d001ca7077d17cf6d8 to your computer and use it in GitHub Desktop.
Calculate total time from the given times (minutes, seconds) format
/**
* Calculate total time from the given times (minutes, seconds) format
* seperated via |
* Show total hours, total minutes, and total seconds
*/
const str = "4,13|3,3|5,27|5,4|5,57|6,20|5,2|2,36|6,21|5,47|14,58|5,59|4,3|5,54|3,57|9,31|3,48|8,1|17,0|13,15|8,30|18,30|10,14|4,28|8,38|16,50|15,1|2,30|14,8|13,5"
// remove the | and make an array
let strippedStr = str.split('|')
// console.log(strippedStr)
// create an array with times from String to Number
let times = strippedStr.map(t =>
// split the string with "," e.g. min,sec to array and convert to Number
t.split(',').map(Number)
)
let totalHrs = 0, totalMins = 0, totalSecs = 0
// Loop over each element to calculate total time
times.forEach((t) => {
let [m, s] = t
if(totalMins >= 60) {
totalMins -= 60
totalHrs++
} else {
totalMins += m
}
if (totalSecs >=60) {
totalSecs -= 60
totalMins++
} else {
totalSecs += s
}
})
// print the result
console.log(
`
|-- Hours: ${totalHrs}
|-- Minutes: ${totalMins}
|-- Seconds: ${totalSecs}
`
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment