0

I have a database of sport results that looks like this:

const database = [{"distance in km": 10, "duration": "00:45:36", "pace": "00:04:34"}];
  1. To calculate the pace value, I have to divide the duration by the number of kilometers, but how do I do that? Whatever method I try, it returns NaN.

  2. How do I perform calculations on multiple duration values? E.g. how do I get an average pace of three runs? (0:05:22, 00:04:54 and 00:05:05 should give an average of 00:05:07)

Milo
  • 3,365
  • 9
  • 30
  • 44
spiex
  • 1
  • Why don't you use integers to represent the duration? – Luca Kiebel Jan 22 '18 at 20:08
  • 1
    "whatever method you try" such as? – Scott Weaver Jan 22 '18 at 20:14
  • I figured turning "00:05:22" into 322 seconds, then performing calculations and finally transforming the end result back into "hh:mm:ss" format might work as a workaround solution, but is there really no easier way to do it? – spiex Jan 22 '18 at 20:15
  • 2
    *"is there easier way"* .... not really other than using a library like moment.js to do all that for you – charlietfl Jan 22 '18 at 20:16
  • https://stackoverflow.com/questions/13262621/how-do-i-use-format-on-a-moment-js-duration – Scott Weaver Jan 22 '18 at 20:17
  • 1
    You can convert those values to integers pretty easily, using the answers [from this question](https://stackoverflow.com/q/9640266/215552) then convert back to your duration format using answers from [this question](https://stackoverflow.com/q/6312993/215552). – Heretic Monkey Jan 22 '18 at 20:28
  • Basically any method to solve this, external library or not, is going to convert string to number, perform math, convert back to string. – James Jan 22 '18 at 20:51

1 Answers1

0

function durationToSeconds(dur) {
dur=dur.toString();
     var hours=parseFloat(dur.substr(0, dur.indexOf(":")));
     var minutes=parseFloat(dur.substr(dur.indexOf(":")+1, dur.lastIndexOf(":")));
     var seconds=parseFloat(dur.substr(dur.lastIndexOf(":")+1));
     return (hours*60*60)+(minutes*60)+(seconds);
}
function secondsToDuration(secs) {
     var hours=Math.floor(secs/(60*60));
     secs-=hours*60*60;
     var minutes=Math.floor(secs/60);
     secs-=minutes*60;
     var seconds=secs;
     return (hours.toString().length===1?"0":"") + hours + ":" + (minutes.toString().length===1?"0":"") + minutes + ":" + (seconds.toString().length===1?"0":"") + seconds;
}
function getPace(t1, speed) {
     var secs1=durationToSeconds(t1);
     return secondsToDuration(Math.round(secs1/speed));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Distance travelled: <input type='number' id='speed'/><br>
Duration: <input type='text' id='time1'/><br>
<button onclick='$("#time2").html(getPace($("#time1").val(), $("#speed").val()))'>Calculate Time</button>
<p id='time2'></p>
MBJH
  • 1,571
  • 3
  • 17
  • 36