Skip to content

Instantly share code, notes, and snippets.

@mdwhatcott
Created November 11, 2022 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdwhatcott/3a7e0939a243b19adb7af57aeca89710 to your computer and use it in GitHub Desktop.
Save mdwhatcott/3a7e0939a243b19adb7af57aeca89710 to your computer and use it in GitHub Desktop.
My own simple, a word which hear means inefficient, implementation of humanize.Comma
package humanize
import (
"fmt"
"strings"
)
// Comma formats a number with commas separating each block of 3 numbers.
// Inspiration: https://pkg.go.dev/github.com/dustin/go-humanize#Comma
func Comma(n int) string {
s := []rune(Reverse(fmt.Sprint(n)))
var b strings.Builder
for x := 0; ; x++ {
b.WriteRune(s[0])
s = s[1:]
if len(s) > 0 && (x+1)%3 == 0 {
b.WriteRune(',')
}
if len(s) == 0 {
return Reverse(b.String())
}
}
}
func Reverse(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
package humanize
import "testing"
func TestCommas(t *testing.T) {
assertEqual(t, "1", Comma(1))
assertEqual(t, "10", Comma(10))
assertEqual(t, "100", Comma(100))
assertEqual(t, "1,000", Comma(1000))
assertEqual(t, "10,000", Comma(10000))
assertEqual(t, "100,000", Comma(100000))
}
func assertEqual(t *testing.T, expected, actual string) {
if actual == expected {
return
}
t.Helper()
t.Errorf("\n"+
"want [%s]"+"\n"+
"got [%s]", actual, expected)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment