Fix the US phone number formatter
Your task
You asked an AI for a phone number formatter, and its first answer imported phone-formatter-pro, a package nobody on your team had heard of. You asked for plain code with no dependencies instead, so you can read every line before it ships.
An assistant wrote format_us_phone(raw). It is in the editor. It has a bug. Find it and fix it.
Input and output:
raw: the phone number as someone typed it. It can hold any characters.- Return the formatted number, or
"invalid".
Rules the tests check:
- Keep only the digits 0 to 9 from
raw, in order. Every other character is ignored. - Exactly 10 digits: return
"(AAA) BBB-CCCC", whereAAAis the first 3 digits,BBBthe next 3 andCCCCthe last 4. - Exactly 11 digits starting with
1: a US number with its country code. Drop the1and return"+1 "followed by the 10 digit format above. - Any other number of digits, or 11 digits that do not start with
1, returns"invalid".
Examples
format_us_phone(raw: str) -> strExample 1
Input
format_us_phone("5551234567")Output
"(555) 123-4567"Example 2
Input
format_us_phone("+1 (555) 123-4567")Output
"+1 (555) 123-4567"