now.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /**
  2. * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. declare const process: any;
  7. declare const window: any;
  8. const now: () => now.Timestamp = (function () {
  9. if (typeof window !== 'undefined' && window.performance) {
  10. const perf = window.performance;
  11. return () => perf.now();
  12. } else if (typeof process !== 'undefined' && process.hrtime !== 'undefined' && typeof process.hrtime === 'function') {
  13. return () => {
  14. const t = process.hrtime();
  15. return t[0] * 1000 + t[1] / 1000000;
  16. };
  17. } else if (Date.now) {
  18. return () => Date.now();
  19. } else {
  20. return () => +new Date();
  21. }
  22. }());
  23. namespace now {
  24. export type Timestamp = number & { '@type': 'now-timestamp' }
  25. }
  26. function formatTimespan(t: number, includeMsZeroes = true) {
  27. if (isNaN(t)) return 'n/a';
  28. let h = Math.floor(t / (60 * 60 * 1000)),
  29. m = Math.floor(t / (60 * 1000) % 60),
  30. s = Math.floor(t / 1000 % 60),
  31. ms = Math.floor(t % 1000).toString();
  32. while (ms.length < 3) ms = '0' + ms;
  33. while (!includeMsZeroes && ms.length > 1 && ms[ms.length - 1] === '0') ms = ms.substr(0, ms.length - 1);
  34. if (h > 0) return `${h}h${m}m${s}.${ms}s`;
  35. if (m > 0) return `${m}m${s}.${ms}s`;
  36. if (s > 0) return `${s}.${ms}s`;
  37. return `${t.toFixed(0)}ms`;
  38. }
  39. export { now, formatTimespan };