Small changes in Hall + data/challengeCheck
[vchess.git] / client / src / data / challengeCheck.js
CommitLineData
8ef2edfa 1// TODO: rename file "timeControl.js" in utils/
9d58ef95
BA
2function timeUnitToSeconds(value, unit)
3{
4 let seconds = value;
5 switch (unit)
6 {
7 case 'd':
8 seconds *= 24;
9 case 'h':
10 seconds *= 60;
11 case 'm':
12 seconds *= 60;
13 }
14 return seconds;
15}
16
17function isLargerUnit(unit1, unit2)
18{
19 return (unit1 == 'd' && unit2 != 'd')
20 || (unit1 == 'h' && ['s','m'].includes(unit2))
21 || (unit1 == 'm' && unit2 == 's');
22}
23
8ef2edfa 24export function extractTime(timeControl)
ab4f4bf2 25{
8ef2edfa
BA
26 const tcParts = timeControl.replace(/ /g,"").split('+');
27 const mainTimeArray = tcParts[0].match(/([0-9]+)([smhd])/);
28 if (!mainTimeArray)
29 return null;
30 const mainTimeValue = parseInt(mainTimeArray[1]);
31 const mainTimeUnit = mainTimeArray[2];
32 const mainTime = timeUnitToSeconds(mainTimeValue, mainTimeUnit);
33 let increment = 0;
9d58ef95
BA
34 if (tcParts.length >= 2)
35 {
36 const increment = tcParts[1].match(/([0-9]+)([smhd])/);
37 if (!increment)
8ef2edfa 38 return null;
9d58ef95
BA
39 const incrementValue = parseInt(increment[1]);
40 const incrementUnit = increment[2];
8ef2edfa 41 // Increment unit cannot be larger than main unit:
9d58ef95 42 if (isLargerUnit(incrementUnit, mainTimeUnit))
8ef2edfa
BA
43 return null;
44 increment = timeUnitToSeconds(incrementValue, incrementUnit);
9d58ef95 45 }
8ef2edfa
BA
46 return {mainTime:mainTime, increment:increment};
47}
48
49// TODO: put this in Hall.vue
50export function checkChallenge(c)
51{
52 const vid = parseInt(c.vid);
53 if (isNaN(vid) || vid <= 0)
54 return "Please select a variant";
55
56 const tc = extractTime(c.timeControl);
57 if (!tc)
58 return "Wrong time control";
ab4f4bf2
BA
59
60 // Basic alphanumeric check for players names
61 let playerCount = 0;
6faa92f2 62 for (const pname of c.to)
ab4f4bf2 63 {
6faa92f2 64 if (pname.length > 0)
ab4f4bf2 65 {
9d58ef95 66 // TODO: slightly redundant (see data/userCheck.js)
6faa92f2 67 if (!pname.match(/^[\w]+$/))
ab4f4bf2
BA
68 return "Wrong characters in players names";
69 playerCount++;
70 }
71 }
72
74ea2e8d 73 if (playerCount > 0 && playerCount != c.nbPlayers-1)
ab4f4bf2
BA
74 return "None, or all of the opponent names must be filled"
75
9d58ef95
BA
76 // Allow custom FEN (and check it) only for individual challenges
77 if (c.fen.length > 0 && playerCount > 0)
78 {
79 if (!V.IsGoodFen(c.fen))
80 return "Bad FEN string";
81 }
ab4f4bf2 82}