Skip to content

Commit

Permalink
Left-pad Freq() output to right-align count values
Browse files Browse the repository at this point in the history
  • Loading branch information
bitfield committed Jul 2, 2019
1 parent 3fc97ad commit b942596
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 6 deletions.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,15 @@ sort testdata/freq.input.txt |uniq -c |sort -rn
script.Stdin().Freq().First(10).Stdout()
```

Like `uniq -c`, `Freq()` left-pads its count values if necessary to make them easier to read:

```
10 apple
4 banana
2 orange
1 kumquat
```

### Join

`Join()` reads its input and replaces newlines with spaces, preserving a terminating newline if there is one.
Expand Down
8 changes: 7 additions & 1 deletion filters.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"os/exec"
"regexp"
"sort"
"strconv"
"strings"
)

Expand Down Expand Up @@ -178,18 +179,23 @@ func (p *Pipe) Freq() *Pipe {
count int
}
var freqs = make([]frequency, 0, len(freq))
var maxCount int
for line, count := range freq {
freqs = append(freqs, frequency{line, count})
if count > maxCount {
maxCount = count
}
}
sort.Slice(freqs, func(i, j int) bool {
if freqs[i].count == freqs[j].count {
return freqs[i].line < freqs[j].line
}
return freqs[i].count > freqs[j].count
})
fieldWidth := len(strconv.Itoa(maxCount))
var output strings.Builder
for _, item := range freqs {
output.WriteString(fmt.Sprintf("%d %s", item.count, item.line))
output.WriteString(fmt.Sprintf("%*d %s", fieldWidth, item.count, item.line))

This comment has been minimized.

Copy link
@breml

breml Jul 2, 2019

I did not know about * for width as argument in fmt.Printf. That is a nice one.

output.WriteRune('\n')
}
return Echo(output.String())
Expand Down
8 changes: 4 additions & 4 deletions testdata/freq.golden.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
4 apple
4 banana
2 orange
1 kumquat
10 apple
4 banana
2 orange
1 kumquat
8 changes: 7 additions & 1 deletion testdata/freq.input.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,10 @@ kumquat
apple
apple
banana
banana
banana
apple
apple
apple
apple
apple
apple

0 comments on commit b942596

Please sign in to comment.