Some bugs fixes. TODO: double disconnect when anonymous reloads page in Hall
[vchess.git] / client / src / utils / timeControl.js
CommitLineData
dd75774d
BA
1function timeUnitToSeconds(value, unit)
2{
3 let seconds = value;
4 switch (unit)
5 {
6 case 'd':
7 seconds *= 24;
8 case 'h':
9 seconds *= 60;
10 case 'm':
11 seconds *= 60;
12 }
13 return seconds;
14}
15
16function isLargerUnit(unit1, unit2)
17{
18 return (unit1 == 'd' && unit2 != 'd')
19 || (unit1 == 'h' && ['s','m'].includes(unit2))
20 || (unit1 == 'm' && unit2 == 's');
21}
22
71468011 23export function extractTime(cadence)
dd75774d 24{
71468011 25 let tcParts = cadence.replace(/ /g,"").split('+');
e64c6f67
BA
26 // Concatenate usual time control suffixes, in case of none is provided
27 tcParts[0] += "m";
28 tcParts[1] += "s";
7f36b53a 29 const mainTimeArray = tcParts[0].match(/^([0-9]+)([smhd]+)$/);
dd75774d
BA
30 if (!mainTimeArray)
31 return null;
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;
36 if (tcParts.length >= 2)
37 {
7f36b53a 38 const incrementArray = tcParts[1].match(/^([0-9]+)([smhd]+)$/);
1efe1d79 39 if (!incrementArray)
dd75774d 40 return null;
1efe1d79 41 const incrementValue = parseInt(incrementArray[1]);
db13014d 42 const incrementUnit = incrementArray[2][0];
dd75774d
BA
43 // Increment unit cannot be larger than main unit:
44 if (isLargerUnit(incrementUnit, mainTimeUnit))
45 return null;
46 increment = timeUnitToSeconds(incrementValue, incrementUnit);
47 }
48 return {mainTime:mainTime, increment:increment};
49}