index.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*!
  2. * pretty-time <https://github.com/jonschlinkert/pretty-time>
  3. *
  4. * Copyright (c) 2015-2018, present, Jon Schlinkert.
  5. * Released under the MIT License.
  6. */
  7. 'use strict';
  8. const utils = require('./utils');
  9. module.exports = (time, smallest, digits) => {
  10. const isNumber = /^[0-9]+$/.test(time);
  11. if (!isNumber && !Array.isArray(time)) {
  12. throw new TypeError('expected an array or number in nanoseconds');
  13. }
  14. if (Array.isArray(time) && time.length !== 2) {
  15. throw new TypeError('expected an array from process.hrtime()');
  16. }
  17. if (/^[0-9]+$/.test(smallest)) {
  18. digits = smallest;
  19. smallest = null;
  20. }
  21. let num = isNumber ? time : utils.nano(time);
  22. let res = '';
  23. let prev;
  24. for (const uom of Object.keys(utils.scale)) {
  25. const step = utils.scale[uom];
  26. let inc = num / step;
  27. if (smallest && utils.isSmallest(uom, smallest)) {
  28. inc = utils.round(inc, digits);
  29. if (prev && (inc === (prev / step))) --inc;
  30. res += inc + uom;
  31. return res.trim();
  32. }
  33. if (inc < 1) continue;
  34. if (!smallest) {
  35. inc = utils.round(inc, digits);
  36. res += inc + uom;
  37. return res;
  38. }
  39. prev = step;
  40. inc = Math.floor(inc);
  41. num -= (inc * step);
  42. res += inc + uom + ' ';
  43. }
  44. return res.trim();
  45. };