-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
73 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} | ||
} |