Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for notation position of progress bar tracker value #180

Merged
merged 3 commits into from
Aug 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 27 additions & 3 deletions progress/units.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,21 @@ import (
"fmt"
)

// UnitsNotationPosition determines units position relative of tracker value
// Defaults is UnitsNotationPositionBefore
type UnitsNotationPosition int

// Supported unit positions relative to tracker value
const (
UnitsNotationPositionBefore UnitsNotationPosition = iota
UnitsNotationPositionAfter
)

// Units defines the "type" of the value being tracked by the Tracker.
type Units struct {
Notation string
Formatter func(value int64) string
NotationPosition UnitsNotationPosition
}

var (
Expand Down Expand Up @@ -52,10 +63,23 @@ var (

// Sprint prints the value as defined by the Units.
func (tu Units) Sprint(value int64) string {
if tu.Formatter == nil {
return tu.Notation + FormatNumber(value)
formatter := tu.Formatter
if formatter == nil {
formatter = FormatNumber
}

formattedValue := formatter(value)

switch tu.NotationPosition {
case UnitsNotationPositionBefore:
return tu.Notation + formattedValue

case UnitsNotationPositionAfter:
return formattedValue + tu.Notation

default:
return tu.Notation + formattedValue
}
return tu.Notation + tu.Formatter(value)
}

// FormatBytes formats the given value as a "Byte".
Expand Down
8 changes: 8 additions & 0 deletions progress/units_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,11 @@ func TestUnits_Sprint(t *testing.T) {
customUnits := Units{Notation: "#"}
assert.Equal(t, "#1.50K", customUnits.Sprint(1500))
}

func TestUnits_NotationPosition(t *testing.T) {
afterUnits := Units{Notation: " ₽", NotationPosition: UnitsNotationPositionAfter}
assert.Equal(t, "1.50K ₽", afterUnits.Sprint(1500))

unknownNotationPosition := Units{Notation: "* ", NotationPosition: UnitsNotationPosition(999)}
assert.Equal(t, "* 1.50K", unknownNotationPosition.Sprint(1500))
}