Code Lab

Count every word

HardMap and Set15 min

Write a function countWords(sentence) that counts how many times every word occurs.

  • Return a Map: the key is the word in lower case, the value is the count.
  • A word is a run of letters and digits (Latin and Cyrillic). Spaces and punctuation separate words.
  • Case does not matter: Test and test are the same word.
  • If there are no words, return an empty Map.
  • Key order is not checked.

Examples

countWords('the cat and the hat')

Returns Map(4) { 'the' => 2, 'cat' => 1, 'and' => 1, 'hat' => 1 }

countWords('Test, test!')

Returns Map(1) { 'test' => 2 }

Source

Loading the editor...
  1. InputcountWords('the cat and the hat')
    ExpectedMap(4) { 'the' => 2, 'cat' => 1, 'and' => 1, 'hat' => 1 }
  2. InputcountWords('Test test TEST')
    ExpectedMap(1) { 'test' => 3 }
  3. InputcountWords('')
    ExpectedMap(0) {}

Hidden tests run on Submit.