cf.completefrontend

Write the codeMedium

Fix the type error in countWords, and make it count every word correctly.

countWords("the cat and the hat") returns { the: 2, cat: 1, and: 1, hat: 1 }. Words are separated by whitespace, and text with no words gives {}. Under strict, TypeScript rejects the code below. Give the result a type, and make sure every word counts correctly, including words like constructor.

Write this
function countWords(text: string) {  const counts = {};  for (const word of text.split(" ")) {    counts[word] = (counts[word] || 0) + 1;  }  return counts;}

Solve it in the editor

The answer

Write it yourself first. Then compare it with a reference solution and the checks it passes.

Checking your sign-in…