仿 common-lang 包的 go 語(yǔ)言工具庫(kù)

common-lang-in-go

https://github.com/sjsdfg/common-lang-in-go

Java 程序員編寫的類似 common-lang 工具包
包名就是要用大駝峰,不想改成 go 規(guī)范的包名。自己寫的任性

how to use

go get github.com/sjsdfg/common-lang-in-go

StringUtils

  • IsEmpty(str string) bool
  • IsNotEmpty(str string) bool
  • IsAllEmpty(list ...string) bool
  • IsAnyEmpty(list ...string) bool
  • IsAnyNoneEmpty(list ...string) bool
  • IsBlank(str string) bool
  • IsNotBlank(str string) bool
  • IsZero(str string) bool
  • IsNotZero(str string) bool
  • IsAnyZero(list ...string) bool
  • IsAllZero(list ...string) bool
  • IsAnyNoneZero(list ...string) bool
  • Equal(str1, str2 string) bool
  • EqualIgnoreCase(str1, str2 string) bool
  • EqualsAny(str string, list ...string) bool
  • EqualsAnyIgnoreCase(str string, list ...string) bool
  • IsDigital(str string) bool
  • DefaultIfEmpty(str, defaultStr string) string
  • If(condition bool, ifTrue, ifFalse string) string
  • Truncate(str string, startIndex, endIndex int) string

CollectionUtils

match functions

  • AllMatch(list interface{}, action matchFunc) bool
  • AnyMatch(list interface{}, action matchFunc) bool
  • NoneMatch(list interface{}, action matchFunc) bool

Use Case

func TestAllMatch(t *testing.T) {
    testCase := []string{"a", "a", "a"}
    assert.Equal(t, true, AllMatch(testCase, func(index int) bool {
        return testCase[index] == "a"
    }))

    testCase = []string{"a", "a", "b"}
    assert.Equal(t, false, AllMatch(testCase, func(index int) bool {
        return testCase[index] == "a"
    }))
}

func TestAnyMatch(t *testing.T) {
    testCase := []string{"a", "a", "b"}
    assert.Equal(t, true, AnyMatch(testCase, func(index int) bool {
        return testCase[index] == "b"
    }))

    testCase = []string{"a", "a", "b"}
    assert.Equal(t, false, AnyMatch(testCase, func(index int) bool {
        return testCase[index] == "c"
    }))
}

func TestNoneMatch(t *testing.T) {
    testCase := []string{"a", "a", "b"}
    assert.Equal(t, true, NoneMatch(testCase, func(index int) bool {
        return testCase[index] == "c"
    }))

    testCase = []string{"a", "a", "b"}
    assert.Equal(t, false, NoneMatch(testCase, func(index int) bool {
        return testCase[index] == "b"
    }))
}

empty judgement

  • IsEmpty(collection interface{})
  • IsNotEmpty(collection interface{}) bool

map function

這個(gè)是由于沒有 Java Stream 里面的 map,導(dǎo)致每次提取某一類型的字段成為數(shù)組,寫的代碼十分冗余。所以抽象出來的。

由于不支持泛型,只能書寫基本類型的方法調(diào)用。不過我的個(gè)人場(chǎng)景就是提取某一個(gè)字段(尤其是 id),目前還夠用。

  • MapToStringSlice(list interface{}, action func(index int) string) []string
  • MapToIntSlice(list interface{}, action func(index int) int) []int
  • MapToInt64Slice(list interface{}, action func(index int) int64) []int64
  • MapToFloat64Slice(list interface{}, action func(index int) float64) []float64
  • MapToFloat32Slice(list interface{}, action func(index int) float32) []float32

Use Case

func TestMapToStringSlice(t *testing.T) {
    students := createStudents()
    timer := TimeUtils.NewTimer()
    reflectSlice := MapToStringSlice(students, func(i int) string {
        return students[i].name
    })
    t.Logf("MapToStringSlice cost %d nanos", timer.GetDurationInNanos())

    timer.Reset()
    nativeSlice := NativeMapToStringSlice(students)
    t.Logf("NativeMapToStringSlice cost %d nanos", timer.GetDurationInNanos())
    assert.Equal(t, nativeSlice, reflectSlice)
}

iterate

  • ForEach(list interface{}, action func(index int)):之前寫 Java 寫慣了,覺得使用 return 代替 continue 是可讀性更高的代碼,因?yàn)榭梢蕴嵩绶祷販p少代碼的嵌套接口。因此抽象出了該方法
func TestForEach(t *testing.T) {
    students := createStudents()
    ForEach(students, func(index int) {
        t.Log(students[index])
    })

    ForEach(students, func(index int) {
        students[index].name = "testing"
    })

    ForEach(students, func(index int) {
        assert.Equal(t, "testing", students[index].name)
    })
}

注意

以上方法類型為 FunctionName(list interface{}, action func(index int)) 均可以替換為 FunctionName(len int, action func(index int))

比如 ForEach 的實(shí)現(xiàn)可以為

func ForEach(len int, action func(i int)) {
    for i := 0; i < len; i++ {
        action(i)
    }
}

這個(gè)版本的運(yùn)行效率更高。但是考慮到邊界檢查的安全性問題,我還是更傾向于傳入 list 進(jìn)來,通過反射來獲取列表的長(zhǎng)度。相關(guān)代碼可查看 https://github.com/sjsdfg/common-lang-in-go/blob/faster/CollectionUtils/collection_utils.go

Float32Utils

  • Max(list ...float32) float32
  • Min(list ...float32) float32
  • If(condition bool, ifTrue, ifFalse float32) float32
  • Abs(a float32) float32
  • Equal(a, b float32) bool

Float64Utils

  • Max(list ...float64) float64
  • Min(list ...float64) float64
  • If(condition bool, ifTrue, ifFalse float64) float64
  • Abs(a float64) float64
  • Equal(a, b float64) bool

Int64Utils

  • Max(list ...int64) int64
  • Min(list ...int64) int64
  • If(condition bool, ifTrue, ifFalse int64) int64
  • Abs(a int64) int64

IntUtils

  • Max(list ...int) int
  • Min(list ...int) int
  • If(condition bool, ifTrue, ifFalse int64) int
  • Abs(a int) int

TimeUtils

  • Max(list ...time.Time) time.Time
  • Min(list ...time.Time) time.Time
  • If(condition bool, ifTrue, ifFalse int64) time.Time

上面的 XxxUtils 根據(jù)類型進(jìn)行抽象,提供了最大值最小值的方法。并且因?yàn)?go 語(yǔ)言沒有提供三目表達(dá)式,提供了 If 方法出來??梢赃厡懗鰜砜勺x性更高的代碼

最佳實(shí)踐

// 待實(shí)現(xiàn)
主要是想配合 IDEA 的 live template 和 Postfix completion 進(jìn)行快捷鍵的搭配。

這樣可以更好的使用該庫(kù)。

Benchmark

CollectionUtils

CollectionUtils#IsEmpty

goos: darwin
goarch: amd64
pkg: github.com/sjsdfg/common-lang-in-go/CollectionUtils
BenchmarkIsEmpty                        22247214            54.3 ns/op
BenchmarkIsEmpty-2                      23466332            51.7 ns/op
BenchmarkIsEmpty-4                      23064122            51.4 ns/op
BenchmarkIsEmpty-8                      23634132            51.5 ns/op
BenchmarkNativeIsEmpty
BenchmarkNativeIsEmpty                  20717202            53.7 ns/op
BenchmarkNativeIsEmpty-2                23106975            50.9 ns/op
BenchmarkNativeIsEmpty-4                22869487            51.1 ns/op
BenchmarkNativeIsEmpty-8                23977856            51.1 ns/op
PASS

CollectionUtils#MapToStringSlice


BenchmarkMapToStringSlice
BenchmarkMapToStringSlice                4942840           292 ns/op
BenchmarkMapToStringSlice-2              4770552           263 ns/op
BenchmarkMapToStringSlice-4              4740819           302 ns/op
BenchmarkMapToStringSlice-8              5007906           238 ns/op
BenchmarkNativeMapToStringSlice
BenchmarkNativeMapToStringSlice         10728244           113 ns/op
BenchmarkNativeMapToStringSlice-2       10394302           113 ns/op
BenchmarkNativeMapToStringSlice-4       10965626           112 ns/op
BenchmarkNativeMapToStringSlice-8       10831770           113 ns/op
PASS
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容