Keine Beschreibung

index.js 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*jshint node:true */
  2. "use strict";
  3. var minimalDesc = ['h', 'min', 's', 'ms', 'μs', 'ns'];
  4. var verboseDesc = ['hour', 'minute', 'second', 'millisecond', 'microsecond', 'nanosecond'];
  5. var convert = [60*60, 60, 1, 1e6, 1e3, 1];
  6. module.exports = function (source, opts) {
  7. var verbose, precise, i, spot, sourceAtStep, valAtStep, decimals, strAtStep, results, totalSeconds;
  8. verbose = false;
  9. precise = false;
  10. if (opts) {
  11. verbose = opts.verbose || false;
  12. precise = opts.precise || false;
  13. }
  14. if (!Array.isArray(source) || source.length !== 2) {
  15. return '';
  16. }
  17. if (typeof source[0] !== 'number' || typeof source[1] !== 'number') {
  18. return '';
  19. }
  20. // normalize source array due to changes in node v5.4+
  21. if (source[1] < 0) {
  22. totalSeconds = source[0] + source[1] / 1e9;
  23. source[0] = parseInt(totalSeconds);
  24. source[1] = parseFloat((totalSeconds % 1).toPrecision(9)) * 1e9;
  25. }
  26. results = '';
  27. // foreach unit
  28. for (i = 0; i < 6; i++) {
  29. spot = i < 3 ? 0 : 1; // grabbing first or second spot in source array
  30. sourceAtStep = source[spot];
  31. if (i !== 3 && i !== 0) {
  32. sourceAtStep = sourceAtStep % convert[i-1]; // trim off previous portions
  33. }
  34. if (i === 2) {
  35. sourceAtStep += source[1]/1e9; // get partial seconds from other portion of the array
  36. }
  37. valAtStep = sourceAtStep / convert[i]; // val at this unit
  38. if (valAtStep >= 1) {
  39. if (verbose) {
  40. valAtStep = Math.floor(valAtStep); // deal in whole units, subsequent laps will get the decimal portion
  41. }
  42. if (!precise) {
  43. // don't fling too many decimals
  44. decimals = valAtStep >= 10 ? 0 : 2;
  45. strAtStep = valAtStep.toFixed(decimals);
  46. } else {
  47. strAtStep = valAtStep.toString();
  48. }
  49. if (strAtStep.indexOf('.') > -1 && strAtStep[strAtStep.length-1] === '0') {
  50. strAtStep = strAtStep.replace(/\.?0+$/,''); // remove trailing zeros
  51. }
  52. if (results) {
  53. results += ' '; // append space if we have a previous value
  54. }
  55. results += strAtStep; // append the value
  56. // append units
  57. if (verbose) {
  58. results += ' '+verboseDesc[i];
  59. if (strAtStep !== '1') {
  60. results += 's';
  61. }
  62. } else {
  63. results += ' '+minimalDesc[i];
  64. }
  65. if (!verbose) {
  66. break; // verbose gets as many groups as necessary, the rest get only one
  67. }
  68. }
  69. }
  70. return results;
  71. };