And we're back with yet another challenge. This one will be from codewars this time. I found it to be somewhat interesting. I wanted to do it to see the other solutions, but first let's define the problem.
Challenge
It's important to note that this will be a U.S. phone number based on the North American number plan. There are specifics set up in the tests that you wouldn't have if checking a valid number in real use cases. For instance, they say that the number will always have parenthesis, a space after the closing parenthesis, & a hyphen in between the last two sections of the phone number. In real use cases, we would expect users to enter phone numbers in many ways. They might not use parenthesis or a hyphen at all, they might separate the digits with periods. Essentially, we would accept different versions of how the number was entered in.
Thought pattern
Because of how the tests are set up, this wasn't hard to figure out. I chose to check the index for valid symbols and the length, that's it.
- The first character(at index 0) will always need to be an opening parenthesis.
- The fifth character(at index 4) will always need to be a closing parenthesis.
- There will always be a space at index 5 according to the problem.
- The character at index 9 will be a hyphen
- The valid length of a phone number according to the tests would be 14 characters long.
If the argument passed meets all of these conditions then we return true, if it doesn't meet one of the conditions it will return false.
function validPhoneNumber(phoneNumber) {
if (phoneNumber[0] != "("
|| phoneNumber[4] != ")"
|| phoneNumber[5] != " "
|| phoneNumber[9] != "-"
|| phoneNumber.length != 14) {
return false;
}
return true;
}
Doing this kinda felt like cheating. But, a solution that passes all the tests is still a solution, no? It also appears that others had this solution as well, so I'll take it.
Interesting solution
This was one of the solutions I found after submitting. It uses regex to test the passed argument. It checks all the same things I checked in the solution above, but in a more confusing way if you don't know regex. Basically, are there parenthesis wrapping a 3-digit number to start? Is there a space followed by another set of 3-digit numbers? Finally, is there a hyphen followed by 4 digits. It uses the test method on the RegExp object, which returns true if all conditions are met in the regular expression.
function validPhoneNumber(phoneNumber){
return /^\(\d{3}\) \d{3}\-\d{4}$/.test(phoneNumber);
}
Thanks for reading!