Problems › TypeScript › text
Count the words that matter
A support tool skims ticket text to see which terms keep coming up, ignoring the little joining words.
- Split on whitespace and compare in lowercase.
- Words shorter than three characters are noise and are left out.
- The result maps each remaining word to how many times it appeared.
wordFrequency(text: string) → map<string, int>
Where you start
function wordFrequency(text: string): Record<string, number> {
}
Worked examples
| Call | Result |
|---|---|
wordFrequency("card declined card") | {"card":2,"declined":1} |
wordFrequency("The the THE") | {"the":3} |
wordFrequency("a an I ok") | {} |
wordFrequency("") | {} |
Hint
Lowercase before counting, or "Payment" and "payment" end up as two entries.
Reference solution in TypeScript
function wordFrequency(text: string): Record<string, number> {
const result: Record<string, number> = {};
for (const w of text.toLowerCase().split(/\s+/)) {
if (w.length < 3) continue;
result[w] = (result[w] || 0) + 1;
}
return result;
}