I did not go the route of regex. Partly b/c I hate regex (who doesn’t) but mostly b/c it was not the way I thought through the pseudo-code as you can see from my code below.
My question pertains to a specific testcase that is failing:
telephoneCheck("555-5555")
should return false.
When I add in a bunch of console.logs
to pin down where it is going wrong, I am able to conclude the following:
After the for loop, the onlyNum
array looks like this: 5,5,5,5,5,5,5.
As expected.
And it’s length is: 7
. Also, as expected.
Then quite inexplicably, when I start testing whether onlyNum
has 10
or 11
digits, onlyNum
becomes this: ["5", "5", "5", "5", "5", "5", "5", empty × 3].
With a length of 10
.
What changed between the 2 console.logs
…??
Your code so far
function telephoneCheck(str) {
//Check all are numbers
//If yes, check that number digits are:
//if 10 return true
//if 11, check first number is 1; return true
//anything else; return false
//If not, check if non-numbers are ( or ) or -
//If yes, check that number digits are:
//10; return true
//if 11, check first number is 1; return true
//anything else; return false
let strAsArray = str.split("");
let onlyNum = [];
for(var i = 0; i < strAsArray.length; i++){
let acceptableChar = (strAsArray[i] === "-" || strAsArray[i] === "(" || strAsArray[i] === ")")
if(!isNaN(strAsArray[i])){
onlyNum.push(strAsArray[i]);
}else if(!acceptableChar) {
return false;
}
}
console.log("This is onlyNum: " + onlyNum);
console.log("And this is onlyNum length: " + onlyNum.length);
if(onlyNum.length = 10 || (onlyNum.length = 11 && onlyNum[0] == 1)){
console.log(onlyNum);
console.log("The length of " + onlyNum + "is: " + onlyNum.length);
return true;
}
return false;
}
// telephoneCheck("555-555-5555");
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/telephone-number-validator