Skip to content

Commit b942596

Browse files
committed
Left-pad Freq() output to right-align count values
1 parent 3fc97ad commit b942596

File tree

4 files changed

+27
-6
lines changed

4 files changed

+27
-6
lines changed

README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -474,6 +474,15 @@ sort testdata/freq.input.txt |uniq -c |sort -rn
474474
script.Stdin().Freq().First(10).Stdout()
475475
```
476476

477+
Like `uniq -c`, `Freq()` left-pads its count values if necessary to make them easier to read:
478+
479+
```
480+
10 apple
481+
4 banana
482+
2 orange
483+
1 kumquat
484+
```
485+
477486
### Join
478487

479488
`Join()` reads its input and replaces newlines with spaces, preserving a terminating newline if there is one.

filters.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"os/exec"
1010
"regexp"
1111
"sort"
12+
"strconv"
1213
"strings"
1314
)
1415

@@ -178,18 +179,23 @@ func (p *Pipe) Freq() *Pipe {
178179
count int
179180
}
180181
var freqs = make([]frequency, 0, len(freq))
182+
var maxCount int
181183
for line, count := range freq {
182184
freqs = append(freqs, frequency{line, count})
185+
if count > maxCount {
186+
maxCount = count
187+
}
183188
}
184189
sort.Slice(freqs, func(i, j int) bool {
185190
if freqs[i].count == freqs[j].count {
186191
return freqs[i].line < freqs[j].line
187192
}
188193
return freqs[i].count > freqs[j].count
189194
})
195+
fieldWidth := len(strconv.Itoa(maxCount))
190196
var output strings.Builder
191197
for _, item := range freqs {
192-
output.WriteString(fmt.Sprintf("%d %s", item.count, item.line))
198+
output.WriteString(fmt.Sprintf("%*d %s", fieldWidth, item.count, item.line))
193199
output.WriteRune('\n')
194200
}
195201
return Echo(output.String())

testdata/freq.golden.txt

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
4 apple
2-
4 banana
3-
2 orange
4-
1 kumquat
1+
10 apple
2+
4 banana
3+
2 orange
4+
1 kumquat

testdata/freq.input.txt

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,10 @@ kumquat
88
apple
99
apple
1010
banana
11-
banana
11+
banana
12+
apple
13+
apple
14+
apple
15+
apple
16+
apple
17+
apple

0 commit comments

Comments
 (0)