Started code review + some fixes (unfinished)
[vchess.git] / client / src / utils / timeControl.js
CommitLineData
6808d7a1 1function timeUnitToSeconds(value, unit) {
dd75774d 2 let seconds = value;
6808d7a1
BA
3 switch (unit) {
4 case "d":
5 seconds *= 86400; //24*60*60
6 break;
7 case "h":
8 seconds *= 3600;
9 break;
10 case "m":
dd75774d 11 seconds *= 60;
6808d7a1 12 break;
dd75774d
BA
13 }
14 return seconds;
15}
16
6808d7a1
BA
17function isLargerUnit(unit1, unit2) {
18 return (
19 (unit1 == "d" && unit2 != "d") ||
20 (unit1 == "h" && ["s", "m"].includes(unit2)) ||
21 (unit1 == "m" && unit2 == "s")
22 );
dd75774d
BA
23}
24
6808d7a1
BA
25export function extractTime(cadence) {
26 let tcParts = cadence.replace(/ /g, "").split("+");
e64c6f67
BA
27 // Concatenate usual time control suffixes, in case of none is provided
28 tcParts[0] += "m";
29 tcParts[1] += "s";
7f36b53a 30 const mainTimeArray = tcParts[0].match(/^([0-9]+)([smhd]+)$/);
6808d7a1 31 if (!mainTimeArray) return null;
dd75774d 32 const mainTimeValue = parseInt(mainTimeArray[1]);
db13014d 33 const mainTimeUnit = mainTimeArray[2][0];
dd75774d
BA
34 const mainTime = timeUnitToSeconds(mainTimeValue, mainTimeUnit);
35 let increment = 0;
6808d7a1 36 if (tcParts.length >= 2) {
7f36b53a 37 const incrementArray = tcParts[1].match(/^([0-9]+)([smhd]+)$/);
6808d7a1 38 if (!incrementArray) return null;
1efe1d79 39 const incrementValue = parseInt(incrementArray[1]);
db13014d 40 const incrementUnit = incrementArray[2][0];
dd75774d 41 // Increment unit cannot be larger than main unit:
6808d7a1 42 if (isLargerUnit(incrementUnit, mainTimeUnit)) return null;
dd75774d
BA
43 increment = timeUnitToSeconds(incrementValue, incrementUnit);
44 }
6808d7a1 45 return { mainTime: mainTime, increment: increment };
dd75774d 46}