b4bac0531465ef2232ec19804aed2d195bb41257
[vchess.git] / client / src / utils / timeControl.js
1 function timeUnitToSeconds(value, unit) {
2 let seconds = value;
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":
11 seconds *= 60;
12 break;
13 }
14 return seconds;
15 }
16
17 // Used only if increment, hence live game: no "day" unit
18 function isLargerUnit(unit1, unit2) {
19 return (
20 (unit1 == "h" && ["s", "m"].includes(unit2)) ||
21 (unit1 == "m" && unit2 == "s")
22 );
23 }
24
25 export function extractTime(cadence) {
26 let tcParts = cadence.replace(/ /g, "").split("+");
27 // Concatenate usual time control suffix, in case of none is provided
28 tcParts[0] += "m";
29 const mainTimeArray = tcParts[0].match(/^([0-9]+)([smhd]+)$/);
30 if (!mainTimeArray) return null;
31 const mainTimeValue = parseInt(mainTimeArray[1]);
32 const mainTimeUnit = mainTimeArray[2][0];
33 const mainTime = timeUnitToSeconds(mainTimeValue, mainTimeUnit);
34 let increment = 0;
35 if (tcParts.length >= 2) {
36 tcParts[1] += "s";
37 const incrementArray = tcParts[1].match(/^([0-9]+)([smhd]+)$/);
38 if (!incrementArray) return null;
39 const incrementValue = parseInt(incrementArray[1]);
40 const incrementUnit = incrementArray[2][0];
41 // Increment unit cannot be larger than main unit:
42 if (isLargerUnit(incrementUnit, mainTimeUnit)) return null;
43 increment = timeUnitToSeconds(incrementValue, incrementUnit);
44 }
45 return { mainTime: mainTime, increment: increment };
46 }