-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
66 lines (53 loc) · 1.64 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const Duration = require("./duration");
class Stopwatch {
constructor() {
this.startTime = null;
this.endTime = null;
}
start() {
this.startTime = process.hrtime();
}
stop() {
if (!this.startTime) {
throw new Error("stopwatch hasn't started yet.");
}
this.endTime = process.hrtime(this.startTime);
}
getDuration() {
if (!this.endTime) {
throw new Error("stopwatch hasn't stopped yet.");
}
const durationInMilliseconds =
this.endTime[0] * 1e3 + this.endTime[1] / 1e6;
const ms = durationInMilliseconds % 1000;
const seconds = Math.floor(durationInMilliseconds / 1000) % 60;
const minutes = Math.floor(durationInMilliseconds / (1000 * 60)) % 60;
const hours = Math.floor(durationInMilliseconds / (1000 * 60 * 60));
return new Duration(hours, minutes, seconds, ms);
}
printDuration() {
const duration = this.getDuration();
let formattedDuration = "";
if (duration.hours > 0) {
formattedDuration += `${duration.hours} h ${duration.minutes} min ${
duration.seconds
} s ${duration.milliseconds.toFixed(2)} ms`;
} else if (duration.minutes > 0) {
formattedDuration += `${duration.minutes} min ${
duration.seconds
} s ${duration.milliseconds.toFixed(2)} ms`;
} else if (duration.seconds > 0) {
formattedDuration += `${
duration.seconds
} s ${duration.milliseconds.toFixed(2)} ms`;
} else {
formattedDuration += `${duration.milliseconds.toFixed(2)} ms`;
}
console.log(formattedDuration);
}
reset() {
this.startTime = null;
this.endTime = null;
}
}
module.exports = Stopwatch;