diff --git a/print.go b/print.go index f3993e3..c1b7ee0 100644 --- a/print.go +++ b/print.go @@ -1,21 +1,31 @@ package redhat -import "fmt" +import ( + "fmt" + "strconv" +) -// Output print out the result with target format +// Output print out the result with proper order and format func (fa *FileAnalyser) Output(topLines int) []string { resultRows := fa.getResultRows(topLines) + maxLength := lengthOfMaxNumberFromDataRows(resultRows) + reverseDataRows(resultRows) outputArray := make([]string, 0, len(resultRows)) - for index := 0; index < len(resultRows); index++ { - outputArray = append(outputArray, fmt.Sprintf("%d %s", resultRows[index].count, resultRows[index].word)) + for _, item := range resultRows { + outputArray = append(outputArray, fmt.Sprintf("%*d %s", maxLength, item.count, item.word)) } return outputArray } +func lengthOfMaxNumberFromDataRows(dataRows []dataRow) int { + countString := strconv.Itoa(dataRows[0].count) + return len(countString) +} + func (fa *FileAnalyser) getResultRows(topLines int) []dataRow { if len(fa.dataRows) < topLines { return fa.dataRows[0:len(fa.dataRows)] diff --git a/print_test.go b/print_test.go index e1d93b1..c30f8d0 100644 --- a/print_test.go +++ b/print_test.go @@ -90,11 +90,11 @@ func TestFileAnalyser_Output(t *testing.T) { dataRows: []dataRow{ { word: "the", - count: 6, + count: 205, }, { word: "of", - count: 6, + count: 16, }, { word: "shape", @@ -122,13 +122,13 @@ func TestFileAnalyser_Output(t *testing.T) { topLines: 10, }, want: []string{ - "1 Help", - "2 Some", - "3 future", - "4 libraries", - "5 shape", - "6 of", - "6 the", + " 1 Help", + " 2 Some", + " 3 future", + " 4 libraries", + " 5 shape", + " 16 of", + "205 the", }, }, }