Skip to content

Commit

Permalink
feat: add the func sortedUniq
Browse files Browse the repository at this point in the history
  • Loading branch information
nguyenvantuan2391996 committed Aug 6, 2023
1 parent f2fbc13 commit c6cb303
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
35 changes: 35 additions & 0 deletions array/sortedUniq.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package array

import (
"reflect"

"github.com/warriors-vn/go-dash/constants"
)

// sortedUniq returns a new slice with only unique elements from the sorted input slice.
// It takes an array-like data structure as input, assumes that the input slice is sorted,
// and returns a new slice containing only unique elements.
// The function returns the new slice and an error if any occurs.
func sortedUniq(array interface{}) (interface{}, error) {
arrValue := reflect.ValueOf(array)

if arrValue.Kind() != reflect.Slice && arrValue.Kind() != reflect.Array {
return nil, constants.ErrNotSlice
}

mapArrValue := make(map[interface{}]int)
for i := 0; i < arrValue.Len(); i++ {
mapArrValue[arrValue.Index(i).Interface()]++
}

result := reflect.MakeSlice(arrValue.Type(), 0, 0)
for i := 0; i < arrValue.Len(); i++ {
element := arrValue.Index(i)
if data, ok := mapArrValue[element.Interface()]; ok && data > 0 {
mapArrValue[element.Interface()] = 0
result = reflect.Append(result, element)
}
}

return result.Interface(), nil
}
36 changes: 36 additions & 0 deletions array/sortedUniq_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package array

import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/warriors-vn/go-dash/constants"
)

func Test_sortedUniq_valid_int(t *testing.T) {
result, err := sortedUniq([]int{1, 1, 2, 3, 4, 4, 5})

assert.Equal(t, []int{1, 2, 3, 4, 5}, result)
assert.Nil(t, err)
}

func Test_sortedUniq_valid_int64(t *testing.T) {
result, err := sortedUniq([]int64{1, 1, 2, 3, 4, 4, 5, 1, 2})

assert.Equal(t, []int64{1, 2, 3, 4, 5}, result)
assert.Nil(t, err)
}

func Test_sortedUniq_valid_string(t *testing.T) {
result, err := sortedUniq([]string{"1", "1", "2", "3", "4", "4", "5"})

assert.Equal(t, []string{"1", "2", "3", "4", "5"}, result)
assert.Nil(t, err)
}

func Test_sortedUniq_invalid_array_not_slice(t *testing.T) {
result, err := sortedUniq(true)

assert.Equal(t, nil, result)
assert.Equal(t, constants.ErrNotSlice, err)
}

0 comments on commit c6cb303

Please sign in to comment.