I was woking on a problem and got stuck and how I should validate a given string input. Here is the original question
I think my approach is ok but I'm stuck on what to do now.
here is my attempt so far:
const solution =(S)=>{
let validParams = {
'--count': '--count',
'--name': '--name',
'--help': '--help'
}
let strToTest;
for(k of validParams){
switch (S.includes(k)) {
case '--help':
return 1
case '--count':
strToTest = parseInt(S.replace(/--count/g,''))
return countValidator(strToTest);
case '--name':
strToTest = S.replace(/--count/g,'')
return nameValidator(strToTest);
default:
return 1
}
}
}
const countValidator = (num) =>{
if(num > 10 && num < 100){
return 0
}
}
const nameValidator = (str) =>{
if(str.length > 3 && str.length < 10){
return 0
}
}
Here the test cases I saw as well:
solution('--count g') // -1
solution('-help name') // -1
solution('--name SOME_NAME --COUNT 10') // 0
solution('--count 44') // 0
You need to split the input into words first, then test the array elements.
You can't return the result of a validator immediately if it succeeds, since you have to keep testing other parameters.
function solution(S) { let params = S.split(/\\s+/).map(str => str.toLowerCase()); // \\s+ matches any amount of whitespace between parameters let result = 0; if (params.includes('--help')) { result = 1; } for (let i = 0; i < params.length; i++) { switch (params[i]) { case "--help": break; case "--count": i++; if (i > params.length) { result--; return result; } let n = parseInt(params[i]); if (isNaN(n) || n < 10 || n > 100) { result--; return result; } break; case "--name": i++; if (i > params.length) { result--; return result; } let str = params[i]; if (str.length < 3 || str.length > 10) { result--; return result; } break; default: result--; return result; } } return result; } console.log(solution('--count g')); // -1 console.log(solution('-help name')); // -1 console.log(solution('--name SOME_NAME --COUNT 10')); // 0 console.log(solution('--count 44')) // 0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.