Fix clocks update
[vchess.git] / client / src / utils / timeControl.js
1 function 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
16 function isLargerUnit(unit1, unit2)
17 {
18 return (unit1 == 'd' && unit2 != 'd')
19 || (unit1 == 'h' && ['s','m'].includes(unit2))
20 || (unit1 == 'm' && unit2 == 's');
21 }
22
23 export function extractTime(timeControl)
24 {
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]+)/);
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 {
38 const incrementArray = tcParts[1].match(/([0-9]+)([smhd]+)/);
39 if (!incrementArray)
40 return null;
41 const incrementValue = parseInt(incrementArray[1]);
42 const incrementUnit = incrementArray[2];
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 }