UNPKG

1.56 kBJavaScriptView Raw
1export class Timer {
2 constructor(now = () => new Date()) {
3 this.now = now;
4 this.markers = Object.create(null);
5 this.start = this.now();
6 }
7 humanReadableElapsed(sinceMarker) {
8 const elapsedSeconds = this.elapsedSeconds(sinceMarker);
9 return Timer.humanReadableElapsedMinutes(elapsedSeconds) + Timer.humanReadableElapsedSeconds(elapsedSeconds);
10 }
11 elapsedSeconds(sinceMarker) {
12 const elapsedMs = this.elapsedMs(sinceMarker);
13 return Math.floor(elapsedMs / 1000);
14 }
15 elapsedMs(sinceMarker) {
16 const marker = sinceMarker && this.markers[sinceMarker];
17 if (marker) {
18 return this.now().getTime() - marker.getTime();
19 }
20 else {
21 return this.now().getTime() - this.start.getTime();
22 }
23 }
24 mark(name) {
25 this.markers[name] = this.now();
26 }
27 static humanReadableElapsedSeconds(elapsedSeconds) {
28 const restSeconds = elapsedSeconds % 60;
29 return this.formatTime('second', restSeconds);
30 }
31 static humanReadableElapsedMinutes(elapsedSeconds) {
32 const elapsedMinutes = Math.floor(elapsedSeconds / 60);
33 if (elapsedMinutes === 0) {
34 return '';
35 }
36 else {
37 return this.formatTime('minute', elapsedMinutes);
38 }
39 }
40 static formatTime(word, elapsed) {
41 const s = elapsed === 1 ? '' : 's';
42 const blank = word === 'minute' ? ' ' : '';
43 return `${elapsed} ${word}${s}${blank}`;
44 }
45}
46//# sourceMappingURL=timer.js.map
\No newline at end of file