The function should get some text on input and return a map in a following format:
("word1" -> 1, "word2" -> 2 ...)
The keys are words from text and the values are representing the number of times the word appeared in the text. We take into a count only words which at least 4 characters long. Special chars are ignored, words are case insensitive.
import scala.collection.mutable.Map
def wordCounter(text: String) = {
var map:Map[String, Int] = Map()
text.toLowerCase.replaceAll("[^a-z ]", "").split(" ").filter(_.length > 3).foreach(x => addWord(map, x))
map
}
def addWord(map: Map[String, Int], word: String) = {
map(word) = map.getOrElse(word, 0) + 1
}
- Is that fine to use mutable in this case?
- Should I always be suspicious about the solutions that require to use mutable and use it only when its problematic to implement it with immutable types?
- I'm doing an extra loop to filter words longer than 3 chars. In my mind this way it looks a bit cleaner than to have a condition in foreach. Should I care more about the performance or readability in my code?