
function duration_to_ms(v) {
  if (v instanceof Object) {
    return (
      (v.days || 0) * 86400000 +
      (v.hours || 0) * 3600000 +
      (v.minutes || 0) * 60000 +
      (v.seconds || 0) * 1000 +
      (v.milliseconds || 0)
    );
  } else {
    return {
      days: 0,
      hours: 0,
      minutes: 0,
      seconds: 0,
      milliseconds: 0
    }
  }
}

function ms_to_duration(v) {
  const days = Math.floor(v / 86400000);
  v %= 86400000;
  const hours = Math.floor(v / 3600000);
  v %= 3600000;
  const minutes = Math.floor(v / 60000);
  v %= 60000;
  const seconds = Math.floor(v / 1000);
  const milliseconds = v % 1000;
  return { days, hours, minutes, seconds, milliseconds };
}

function normalise_duration (v) {
  return ms_to_duration(duration_to_ms(v));
}

function add_durations(a, b) {
  return ms_to_duration(duration_to_ms(a) + duration_to_ms(b));
}

export {
  duration_to_ms,
  ms_to_duration,
  normalise_duration,
  add_durations
}
