| 1 | // TODO: rename file "timeControl.js" in utils/ |
| 2 | function 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 | |
| 17 | function isLargerUnit(unit1, unit2) |
| 18 | { |
| 19 | return (unit1 == 'd' && unit2 != 'd') |
| 20 | || (unit1 == 'h' && ['s','m'].includes(unit2)) |
| 21 | || (unit1 == 'm' && unit2 == 's'); |
| 22 | } |
| 23 | |
| 24 | export function extractTime(timeControl) |
| 25 | { |
| 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; |
| 34 | if (tcParts.length >= 2) |
| 35 | { |
| 36 | const increment = tcParts[1].match(/([0-9]+)([smhd])/); |
| 37 | if (!increment) |
| 38 | return null; |
| 39 | const incrementValue = parseInt(increment[1]); |
| 40 | const incrementUnit = increment[2]; |
| 41 | // Increment unit cannot be larger than main unit: |
| 42 | if (isLargerUnit(incrementUnit, mainTimeUnit)) |
| 43 | return null; |
| 44 | increment = timeUnitToSeconds(incrementValue, incrementUnit); |
| 45 | } |
| 46 | return {mainTime:mainTime, increment:increment}; |
| 47 | } |
| 48 | |
| 49 | // TODO: put this in Hall.vue |
| 50 | export 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"; |
| 59 | |
| 60 | // Basic alphanumeric check for players names |
| 61 | let playerCount = 0; |
| 62 | for (const pname of c.to) |
| 63 | { |
| 64 | if (pname.length > 0) |
| 65 | { |
| 66 | // TODO: slightly redundant (see data/userCheck.js) |
| 67 | if (!pname.match(/^[\w]+$/)) |
| 68 | return "Wrong characters in players names"; |
| 69 | playerCount++; |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | if (playerCount > 0 && playerCount != c.nbPlayers-1) |
| 74 | return "None, or all of the opponent names must be filled" |
| 75 | |
| 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 | } |
| 82 | } |