DEV Community

SpeediDash
SpeediDash

Posted on Fully Autonomous

A Forgiving Speed, Distance and Time Calculator in JavaScript (It Reads "1h 25m")

The maths behind a speed, distance and time calculator fits on a sticky note: speed = distance / time. The hard part is the input. People type 1:25:30, 85 min, 1h 25m or 1.5h, and mix kilometres, miles and knots.

This post builds a small solver that accepts all of those, converts everything to SI units internally, and gives the missing value back in the units the user chose.

The approach

  1. Normalise every input to SI units: metres, seconds, metres per second.
  2. Solve for whichever of the three values is missing.
  3. Convert the answer back to the user's units and format the time for humans.

Working in SI internally means you never multiply km/h by minutes by accident.

The code

// Distances in metres per unit, speeds in metres per second per unit
const DIST = { m: 1, km: 1000, mi: 1609.344, nmi: 1852, ft: 0.3048 };
const SPEED = { 'm/s': 1, 'km/h': 1000 / 3600, mph: 1609.344 / 3600, kn: 1852 / 3600, 'ft/s': 0.3048 };

// Accepts "1:25:30", "25:30", "1h 25m", "85 min", "90s", "1.5h" -> seconds
function parseDuration(input) {
  const s = String(input).trim().toLowerCase();
  if (/^\d+(:\d{1,2}){1,2}$/.test(s)) {
    const parts = s.split(':').map(Number);
    while (parts.length < 3) parts.unshift(0);
    const [h, m, sec] = parts;
    return h * 3600 + m * 60 + sec;
  }
  const re = /(\d+(?:\.\d+)?)\s*(h|hr|hrs|hours?|m|min|mins|minutes?|s|sec|secs|seconds?)/g;
  let total = 0, matched = false, m;
  while ((m = re.exec(s))) {
    matched = true;
    const n = parseFloat(m[1]);
    const u = m[2][0];
    total += u === 'h' ? n * 3600 : u === 'm' ? n * 60 : n;
  }
  if (!matched) throw new Error(`Can't read a duration from "${input}"`);
  return total;
}

function formatDuration(sec) {
  const t = Math.round(sec);
  const h = Math.floor(t / 3600), m = Math.floor((t % 3600) / 60), s = t % 60;
  return h ? `${h}h ${String(m).padStart(2, '0')}m` : `${m}m ${String(s).padStart(2, '0')}s`;
}

// Give exactly two of { distance, time, speed }; returns all three
function solve({ distance, distanceUnit = 'km', time, speed, speedUnit = 'km/h' }) {
  const given = [distance, time, speed].filter(v => v !== undefined).length;
  if (given !== 2) throw new Error('Give exactly two of distance, time and speed');
  let d = distance !== undefined ? distance * DIST[distanceUnit] : undefined; // metres
  let t = time !== undefined ? parseDuration(time) : undefined;              // seconds
  let v = speed !== undefined ? speed * SPEED[speedUnit] : undefined;        // m/s
  if (d === undefined) d = v * t;
  else if (t === undefined) t = d / v;
  else v = d / t;
  return {
    distance: +(d / DIST[distanceUnit]).toFixed(3),
    time: formatDuration(t),
    speed: +(v / SPEED[speedUnit]).toFixed(2),
  };
}
Enter fullscreen mode Exit fullscreen mode

A few details worth calling out:

  • Durations with colons are read as h:mm:ss or mm:ss, so 25:30 is 25 minutes 30 seconds, not 25 hours.
  • Unit words only need their first letter: h, hr and hours all mean hours.
  • Exactly two inputs are required. Passing one or three is almost always a bug in the calling UI, so it throws.

Trying it

solve({ distance: 10, time: '52 min' });
// { distance: 10, time: '52m 00s', speed: 11.54 }

solve({ distance: 26.2, distanceUnit: 'mi', speed: 6, speedUnit: 'mph' });
// { distance: 26.2, time: '4h 22m', speed: 6 }

solve({ time: '1h 25m', speed: 18 });
// { distance: 25.5, time: '1h 25m', speed: 18 }
Enter fullscreen mode Exit fullscreen mode

The marathon example is a nice sanity check: 26.2 miles at 6 mph is 4.37 hours, which formats as 4h 22m.

Things I'd add next

  • Average speed over legs. Sum the distances and the times, then divide. Averaging the speeds is wrong whenever legs take different amounts of time.
  • Pace output for runners: minutes per km is just 60 / speedKmh.
  • Input validation that tells the user which field it couldn't read, instead of throwing.

If you want to see a version with a UI, unit switching and worked examples, the SpeediDash speed, distance and time calculator is built on the same idea, and runs entirely in the browser. For the maths done by hand, I also wrote up 8 worked speed, distance and time word problems.

Top comments (0)