| 3 | 3 | // convenience to get you started writing code faster. |
| 4 | 4 | // |
| 5 | 5 | |
| 6 | | export const clean = () => { |
| 7 | | throw new Error('Remove this line and implement the function'); |
| 6 | export const clean = (phoneNumber) => { |
| 7 | // Edge Case: Empty or null input |
| 8 | if (!phoneNumber) { |
| 9 | throw new Error('Must not be fewer than 10 digits'); |
| 10 | } |
| 11 | |
| 12 | // Check for letters first |
| 13 | if (/[a-zA-Z]/.test(phoneNumber)) { |
| 14 | throw new Error('Letters not permitted'); |
| 15 | } |
| 16 | |
| 17 | // Check for invalid punctuation (anything not digit, space, or valid phone punctuation) |
| 18 | // Valid punctuation: + - ( ) . and spaces |
| 19 | if (/[^0-9+\-\(\)\.\s]/.test(phoneNumber)) { |
| 20 | throw new Error('Punctuations not permitted'); |
| 21 | } |
| 22 | |
| 23 | // Remove all non-numeric characters |
| 24 | let cleaned = phoneNumber.replace(/\D/g, ''); |
| 25 | |
| 26 | // Check digit count before country code handling |
| 27 | if (cleaned.length < 10) { |
| 28 | throw new Error('Must not be fewer than 10 digits'); |
| 29 | } |
| 30 | |
| 31 | if (cleaned.length > 11) { |
| 32 | throw new Error('Must not be greater than 11 digits'); |
| 33 | } |
| 34 | |
| 35 | if (cleaned.length === 11) { |
| 36 | if (cleaned[0] !== '1') { |
| 37 | throw new Error('11 digits must start with 1'); |
| 38 | } |
| 39 | // Remove the country code |
| 40 | cleaned = cleaned.substring(1); |
| 41 | } |
| 42 | |
| 43 | // Now we should have exactly 10 digits |
| 44 | if (cleaned.length !== 10) { |
| 45 | throw new Error('Must not be fewer than 10 digits'); |
| 46 | } |
| 47 | |
| 48 | // Validate area code (first digit must be 2-9) |
| 49 | if (cleaned[0] === '0') { |
| 50 | throw new Error('Area code cannot start with zero'); |
| 51 | } |
| 52 | if (cleaned[0] === '1') { |
| 53 | throw new Error('Area code cannot start with one'); |
| 54 | } |
| 55 | |
| 56 | // Validate exchange code (4th digit must be 2-9) |
| 57 | if (cleaned[3] === '0') { |
| 58 | throw new Error('Exchange code cannot start with zero'); |
| 59 | } |
| 60 | if (cleaned[3] === '1') { |
| 61 | throw new Error('Exchange code cannot start with one'); |
| 62 | } |
| 63 | |
| 64 | return cleaned; |
| 8 | 65 | }; |
| 66 | |
| 67 | // Handled Edge Cases: empty/null input, incorrect number length, invalid area code, invalid exchange code, non-numeric characters, country code handling |