now.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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 var process: any;
  7. declare var 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) {
  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. if (h > 0) return `${h}h${m}m${s}.${ms}s`;
  34. if (m > 0) return `${m}m${s}.${ms}s`;
  35. if (s > 0) return `${s}.${ms}s`;
  36. return `${t.toFixed(0)}ms`;
  37. }
  38. export { now, formatTimespan }