Skip to content

Commit

Permalink
add variadic parameters to ANSI.With, Apply, NewBuilder and `Bu…
Browse files Browse the repository at this point in the history
…ilder.With`
  • Loading branch information
yamada-wacul committed Jan 11, 2017
1 parent f268d39 commit 7792b9c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 10 deletions.
27 changes: 21 additions & 6 deletions ansi.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package aec

import (
"fmt"
"strings"
)

const esc = "\x1b["
Expand All @@ -15,8 +16,8 @@ var empty = newAnsi("")
type ANSI interface {
fmt.Stringer

// With adapts a given ANSI.
With(ANSI) ANSI
// With adapts given ANSIs.
With(...ANSI) ANSI

// Apply wraps given string in ANSI.
Apply(string) string
Expand All @@ -29,10 +30,8 @@ func newAnsi(s string) *ansiImpl {
return &r
}

func (a *ansiImpl) With(ansi ANSI) ANSI {
s := a.String() + ansi.String()
r := ansiImpl(s)
return &r
func (a *ansiImpl) With(ansi ...ANSI) ANSI {
return concat(append([]ANSI{a}, ansi...))
}

func (a *ansiImpl) Apply(s string) string {
Expand All @@ -42,3 +41,19 @@ func (a *ansiImpl) Apply(s string) string {
func (a *ansiImpl) String() string {
return string(*a)
}

// Apply wraps given string in ANSIs.
func Apply(s string, ansi ...ANSI) string {
if len(ansi) == 0 {
return s
}
return concat(ansi).Apply(s)
}

func concat(ansi []ANSI) ANSI {
strs := make([]string, 0, len(ansi))
for _, p := range ansi {
strs = append(strs, p.String())
}
return newAnsi(strings.Join(strs, ""))
}
8 changes: 4 additions & 4 deletions builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ type Builder struct {
var EmptyBuilder *Builder

// NewBuilder creates a Builder from existing ANSI.
func NewBuilder(a ANSI) *Builder {
return &Builder{a}
func NewBuilder(a ...ANSI) *Builder {
return &Builder{concat(a)}
}

// With is a syntax for With.
func (builder *Builder) With(a ANSI) *Builder {
return NewBuilder(builder.ANSI.With(a))
func (builder *Builder) With(a ...ANSI) *Builder {
return NewBuilder(builder.ANSI.With(a...))
}

// Up is a syntax for Up.
Expand Down

0 comments on commit 7792b9c

Please sign in to comment.