ms.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|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 'y':
  44. return n * y;
  45. case 'days':
  46. case 'day':
  47. case 'd':
  48. return n * d;
  49. case 'hours':
  50. case 'hour':
  51. case 'h':
  52. return n * h;
  53. case 'minutes':
  54. case 'minute':
  55. case 'm':
  56. return n * m;
  57. case 'seconds':
  58. case 'second':
  59. case 's':
  60. return n * s;
  61. case 'ms':
  62. return n;
  63. }
  64. }
  65. /**
  66. * Short format for `ms`.
  67. *
  68. * @param {Number} ms
  69. * @return {String}
  70. * @api private
  71. */
  72. function short(ms) {
  73. if (ms >= d) return Math.round(ms / d) + 'd';
  74. if (ms >= h) return Math.round(ms / h) + 'h';
  75. if (ms >= m) return Math.round(ms / m) + 'm';
  76. if (ms >= s) return Math.round(ms / s) + 's';
  77. return ms + 'ms';
  78. }
  79. /**
  80. * Long format for `ms`.
  81. *
  82. * @param {Number} ms
  83. * @return {String}
  84. * @api private
  85. */
  86. function long(ms) {
  87. return plural(ms, d, 'day')
  88. || plural(ms, h, 'hour')
  89. || plural(ms, m, 'minute')
  90. || plural(ms, s, 'second')
  91. || ms + ' ms';
  92. }
  93. /**
  94. * Pluralization helper.
  95. */
  96. function plural(ms, n, name) {
  97. if (ms < n) return;
  98. if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
  99. return Math.ceil(ms / n) + ' ' + name + 's';
  100. }