c4a229506c81cbe3a84b4ed4548621436429fbf9
[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 const tcParts = timeControl.replace(/ /g,"").split('+');
26 const mainTimeArray = tcParts[0].match(/([0-9]+)([smhd])/);
27 if (!mainTimeArray)
28 return null;
29 const mainTimeValue = parseInt(mainTimeArray[1]);
30 const mainTimeUnit = mainTimeArray[2];
31 const mainTime = timeUnitToSeconds(mainTimeValue, mainTimeUnit);
32 let increment = 0;
33 if (tcParts.length >= 2)
34 {
35 const increment = tcParts[1].match(/([0-9]+)([smhd])/);
36 if (!increment)
37 return null;
38 const incrementValue = parseInt(increment[1]);
39 const incrementUnit = increment[2];
40 // Increment unit cannot be larger than main unit:
41 if (isLargerUnit(incrementUnit, mainTimeUnit))
42 return null;
43 increment = timeUnitToSeconds(incrementValue, incrementUnit);
44 }
45 return {mainTime:mainTime, increment:increment};
46 }