You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123 lines
2.2 KiB

7 years ago
  1. /**
  2. * Helpers.
  3. */
  4. var s = 1000;
  5. var m = s * 60;
  6. var h = m * 60;
  7. var d = h * 24;
  8. var y = d * 365.25;
  9. /**
  10. * Parse or format the given `val`.
  11. *
  12. * Options:
  13. *
  14. * - `long` verbose formatting [false]
  15. *
  16. * @param {String|Number} val
  17. * @param {Object} options
  18. * @return {String|Number}
  19. * @api public
  20. */
  21. module.exports = function(val, options){
  22. options = options || {};
  23. if ('string' == typeof val) return parse(val);
  24. return options.long
  25. ? long(val)
  26. : short(val);
  27. };
  28. /**
  29. * Parse the given `str` and return milliseconds.
  30. *
  31. * @param {String} str
  32. * @return {Number}
  33. * @api private
  34. */
  35. function parse(str) {
  36. var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);
  37. if (!match) return;
  38. var n = parseFloat(match[1]);
  39. var type = (match[2] || 'ms').toLowerCase();
  40. switch (type) {
  41. case 'years':
  42. case 'year':
  43. case 'yrs':
  44. case 'yr':
  45. case 'y':
  46. return n * y;
  47. case 'days':
  48. case 'day':
  49. case 'd':
  50. return n * d;
  51. case 'hours':
  52. case 'hour':
  53. case 'hrs':
  54. case 'hr':
  55. case 'h':
  56. return n * h;
  57. case 'minutes':
  58. case 'minute':
  59. case 'mins':
  60. case 'min':
  61. case 'm':
  62. return n * m;
  63. case 'seconds':
  64. case 'second':
  65. case 'secs':
  66. case 'sec':
  67. case 's':
  68. return n * s;
  69. case 'milliseconds':
  70. case 'millisecond':
  71. case 'msecs':
  72. case 'msec':
  73. case 'ms':
  74. return n;
  75. }
  76. }
  77. /**
  78. * Short format for `ms`.
  79. *
  80. * @param {Number} ms
  81. * @return {String}
  82. * @api private
  83. */
  84. function short(ms) {
  85. if (ms >= d) return Math.round(ms / d) + 'd';
  86. if (ms >= h) return Math.round(ms / h) + 'h';
  87. if (ms >= m) return Math.round(ms / m) + 'm';
  88. if (ms >= s) return Math.round(ms / s) + 's';
  89. return ms + 'ms';
  90. }
  91. /**
  92. * Long format for `ms`.
  93. *
  94. * @param {Number} ms
  95. * @return {String}
  96. * @api private
  97. */
  98. function long(ms) {
  99. return plural(ms, d, 'day')
  100. || plural(ms, h, 'hour')
  101. || plural(ms, m, 'minute')
  102. || plural(ms, s, 'second')
  103. || ms + ' ms';
  104. }
  105. /**
  106. * Pluralization helper.
  107. */
  108. function plural(ms, n, name) {
  109. if (ms < n) return;
  110. if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
  111. return Math.ceil(ms / n) + ' ' + name + 's';
  112. }