Small fixes
[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
23export function extractTime(timeControl)
24{
e64c6f67
BA
25 let tcParts = timeControl.replace(/ /g,"").split('+');
26 // Concatenate usual time control suffixes, in case of none is provided
27 tcParts[0] += "m";
28 tcParts[1] += "s";
29 const mainTimeArray = tcParts[0].match(/([0-9]+)([smhd]+)/);
dd75774d
BA
30 if (!mainTimeArray)
31 return null;
32 const mainTimeValue = parseInt(mainTimeArray[1]);
33 const mainTimeUnit = mainTimeArray[2];
34 const mainTime = timeUnitToSeconds(mainTimeValue, mainTimeUnit);
35 let increment = 0;
36 if (tcParts.length >= 2)
37 {
e64c6f67 38 const incrementArray = tcParts[1].match(/([0-9]+)([smhd]+)/);
1efe1d79 39 if (!incrementArray)
dd75774d 40 return null;
1efe1d79
BA
41 const incrementValue = parseInt(incrementArray[1]);
42 const incrementUnit = incrementArray[2];
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}