-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
misc.js
93 lines (74 loc) · 2.06 KB
/
misc.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/**
* Formats the Time to be nicely formatted for printing to the user.
* @param {*} seconds
* @returns the formatted time as a string
*/
export function formatTime(seconds) {
let text = "";
let secondsLeft = seconds;
let hours = Math.floor(secondsLeft / 3600);
secondsLeft -= hours * 3600;
let minutes = Math.floor(secondsLeft / 60);
secondsLeft -= minutes * 60;
secondsLeft = Math.floor(secondsLeft);
if (hours > 0) {
text += hours.toString();
text += ":";
}
if (minutes < 10 && hours > 0) {
text += "0";
}
text += minutes.toString();
text += ":";
if (secondsLeft < 10) {
text += "0";
}
text += secondsLeft.toString();
return text;
}
/**
* Takes a Time String like 2:47 (2min 47) and returns the time in seconds.
* @param {*} text a string like 2:47 or 1:12:10 (1h, 12min, 10sec)
*/
function parseTimeInput(text) {
const timeArray = text.split(":");
let timerSeconds = 0;
for (let i = 0; i < timeArray.length; i++) {
let time = timeArray[timeArray.length - 1 - i];
let timeValue = parseInt(time);
// Seconds
if (i == 0) {
timerSeconds += timeValue;
// Minutes
} else if (i == 1) {
timerSeconds += timeValue * 60;
// Hours
} else if (i == 2) {
timerSeconds += timeValue * 60 * 60;
}
}
return timerSeconds;
}
// Handles colon insertion
function timeInputColonHandler(text) {
// filter all characters except 0-9
let numberString = "";
for (let i = 0; i < text.length; i++) {
let c = text[i];
if (c >= '0' && c <= '9') {
numberString += c;
}
}
let numIndex = 0;
let finalText = "";
// After every second number, add a colon
for (let i = numberString.length - 1; i >= 0; i--) {
numIndex++;
if (numIndex == 3) {
numIndex = 1;
finalText = ":" + finalText;
}
finalText = numberString[i] + finalText;
}
return finalText;
}