Skip to content

Commit

Permalink
add cpf formatter
Browse files Browse the repository at this point in the history
  • Loading branch information
ftfetter committed Oct 4, 2019
1 parent 241764b commit 69484a6
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
38 changes: 38 additions & 0 deletions cpf/formatter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package cpf

import (
"bytes"
"fmt"

"github.com/brazilian-utils/brutils-go/helpers"
)

var dotIndexes = []int{3, 6}
var hyphenIndexes = []int{9}

// Format returns the CPF with all the "." and "-"
func Format(cpf string) string {
cpfNumbers := helpers.OnlyNumbers(cpf)

// Truncate the CPF to its maximum size
if len(cpfNumbers) > cpfSize {
cpfNumbers = cpfNumbers[:cpfSize]
}

return format(cpfNumbers)
}

func format(nomalizedCpf string) string {
buf := bytes.Buffer{}
for index, character := range nomalizedCpf {
if helpers.ContainsInt(dotIndexes, index) {
buf.WriteString(".")
}
if helpers.ContainsInt(hyphenIndexes, index) {
buf.WriteString("-")
}
buf.WriteString(fmt.Sprintf("%c", character))
}

return buf.String()
}
35 changes: 35 additions & 0 deletions cpf/formatter_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package cpf_test

import (
"testing"

"github.com/brazilian-utils/brutils-go/cpf"
)

var formatTestValues = []struct {
input string
expected string
}{
{"", ""},
{"9", "9"},
{"94", "94"},
{"943", "943"},
{"9438", "943.8"},
{"94389", "943.89"},
{"943895", "943.895"},
{"9438957", "943.895.7"},
{"94389575", "943.895.75"},
{"943895751", "943.895.751"},
{"9438957510", "943.895.751-0"},
{"94389575104", "943.895.751-04"},
{"94389575104000000", "943.895.751-04"},
{"943.?ABC895.751-04abc", "943.895.751-04"},
}

func TestFormat(t *testing.T) {
for _, table := range formatTestValues {
if res := cpf.Format(table.input); res != table.expected {
t.Errorf("Failing for %v \t Expected: %v | Received: %v", table.input, table.expected, res)
}
}
}

0 comments on commit 69484a6

Please sign in to comment.