Fix Eightpieces
[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
92240cf0 17// Used only if increment, hence live game: no "day" unit
6808d7a1
BA
18function isLargerUnit(unit1, unit2) {
19 return (
6808d7a1
BA
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("+");
92240cf0 27 // Concatenate usual time control suffix, in case of none is provided
e64c6f67 28 tcParts[0] += "m";
7f36b53a 29 const mainTimeArray = tcParts[0].match(/^([0-9]+)([smhd]+)$/);
6808d7a1 30 if (!mainTimeArray) return null;
e50a8025 31 const mainTimeValue = parseInt(mainTimeArray[1], 10);
db13014d 32 const mainTimeUnit = mainTimeArray[2][0];
dd75774d
BA
33 const mainTime = timeUnitToSeconds(mainTimeValue, mainTimeUnit);
34 let increment = 0;
6808d7a1 35 if (tcParts.length >= 2) {
7ba4a5bc
BA
36 // Correspondance games don't use an increment:
37 if (mainTimeUnit == 'd') return null;
92240cf0 38 tcParts[1] += "s";
7f36b53a 39 const incrementArray = tcParts[1].match(/^([0-9]+)([smhd]+)$/);
6808d7a1 40 if (!incrementArray) return null;
e50a8025 41 const incrementValue = parseInt(incrementArray[1], 10);
db13014d 42 const incrementUnit = incrementArray[2][0];
dd75774d 43 // Increment unit cannot be larger than main unit:
6808d7a1 44 if (isLargerUnit(incrementUnit, mainTimeUnit)) return null;
dd75774d
BA
45 increment = timeUnitToSeconds(incrementValue, incrementUnit);
46 }
6808d7a1 47 return { mainTime: mainTime, increment: increment };
dd75774d 48}