Skip to content

Commit

Permalink
use FieldsFunc method and benchmark optimizations
Browse files Browse the repository at this point in the history
  • Loading branch information
Andrey Kiselev committed Jun 13, 2020
1 parent b78e537 commit 95d1757
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
12 changes: 8 additions & 4 deletions hw03_frequency_analysis/top.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ import (
"regexp"
"sort"
"strings"
"unicode"
)

var SplitFilter = regexp.MustCompile(`[\s?!.;,]`)
var IgnoredSymbols = regexp.MustCompile(`[-]`)
var ignoredSymbols = regexp.MustCompile(`[-]`)

type WordFrequency struct {
word string
Expand All @@ -20,8 +20,8 @@ func Top10(inputLine string) []string {

// prepare map with counter
freqMap := make(map[string]int)
for _, word := range SplitFilter.Split(inputLine, -1) {
word = IgnoredSymbols.ReplaceAllString(word, "")
inputLine = ignoredSymbols.ReplaceAllString(inputLine, "")
for _, word := range strings.FieldsFunc(inputLine, splitFunc) {
if len(word) > 0 {
freqMap[strings.ToLower(word)]++
}
Expand All @@ -46,3 +46,7 @@ func Top10(inputLine string) []string {

return mostFrequentWords
}

func splitFunc(char rune) bool {
return unicode.IsPunct(char) || unicode.IsSpace(char)
}
6 changes: 6 additions & 0 deletions hw03_frequency_analysis/top_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,9 @@ func TestExtendedTop10(t *testing.T) {
assert.Equal(t, result, testCase.expected)
}
}

func BenchmarkTop(b *testing.B) {
for i := 0; i < b.N; i++ {
Top10(text)
}
}

0 comments on commit 95d1757

Please sign in to comment.