| 3 | 3 | // convenience to get you started writing code faster. |
| 4 | 4 | // |
| 5 | 5 | |
| 6 | | export const countWords = () => { |
| 7 | | throw new Error('Remove this line and implement the function'); |
| 6 | export const countWords = (phrase) => { |
| 7 | // Edge Case: empty input string |
| 8 | if (!phrase || phrase.length === 0) { |
| 9 | return {}; |
| 10 | } |
| 11 | |
| 12 | // Convert to lowercase for case insensitivity |
| 13 | const lowerPhrase = phrase.toLowerCase(); |
| 14 | |
| 15 | // Split by any character that is not a letter, number, or apostrophe |
| 16 | // This preserves contractions while splitting on other punctuation and whitespace |
| 17 | const words = lowerPhrase.split(/[^a-z0-9']+/); |
| 18 | |
| 19 | // Create result object to store word counts |
| 20 | const wordCounts = {}; |
| 21 | |
| 22 | // Process each word |
| 23 | for (const word of words) { |
| 24 | // Edge Case: empty string after split |
| 25 | if (word === '') continue; |
| 26 | |
| 27 | // Edge Case: word that is only apostrophes |
| 28 | if (word.match(/^'+$/)) continue; |
| 29 | |
| 30 | // Edge Case: remove leading and trailing apostrophes (not part of contractions) |
| 31 | const cleanedWord = word.replace(/^'+|'+$/g, ''); |
| 32 | |
| 33 | // Edge Case: word becomes empty after cleaning apostrophes |
| 34 | if (cleanedWord === '') continue; |
| 35 | |
| 36 | // Increment count for the word |
| 37 | wordCounts[cleanedWord] = (wordCounts[cleanedWord] || 0) + 1; |
| 38 | } |
| 39 | |
| 40 | return wordCounts; |
| 8 | 41 | }; |
| 42 | |
| 43 | // Handled Edge Cases: empty input string, empty string after split, word that is only apostrophes, leading/trailing apostrophes, word becomes empty after cleaning apostrophes |