duration.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.duration = void 0;
  4. /**
  5. * Represent a duration in seconds as a string
  6. *
  7. * @param value A finite number, or its string representation
  8. * @return Includes one or two `:` separators, and matches the pattern
  9. * `hhhh:mm:ss`, possibly with a leading `-` for negative values and a
  10. * trailing `.sss` part for non-integer input
  11. *
  12. * @example
  13. * ```js
  14. * var mf = new MessageFormat();
  15. *
  16. * mf.compile('It has been {D, duration}')({ D: 123 })
  17. * // 'It has been 2:03'
  18. *
  19. * mf.compile('Countdown: {D, duration}')({ D: -151200.42 })
  20. * // 'Countdown: -42:00:00.420'
  21. * ```
  22. */
  23. function duration(value) {
  24. if (typeof value !== 'number')
  25. value = Number(value);
  26. if (!isFinite(value))
  27. return String(value);
  28. var sign = '';
  29. if (value < 0) {
  30. sign = '-';
  31. value = Math.abs(value);
  32. }
  33. else {
  34. value = Number(value);
  35. }
  36. var sec = value % 60;
  37. var parts = [Math.round(sec) === sec ? sec : sec.toFixed(3)];
  38. if (value < 60) {
  39. parts.unshift(0); // at least one : is required
  40. }
  41. else {
  42. value = Math.round((value - Number(parts[0])) / 60);
  43. parts.unshift(value % 60); // minutes
  44. if (value >= 60) {
  45. value = Math.round((value - Number(parts[0])) / 60);
  46. parts.unshift(value); // hours
  47. }
  48. }
  49. var first = parts.shift();
  50. return (sign +
  51. first +
  52. ':' +
  53. parts.map(function (n) { return (n < 10 ? '0' + String(n) : String(n)); }).join(':'));
  54. }
  55. exports.duration = duration;