Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add a unique function #26

Open
roosteracham opened this issue Apr 11, 2024 · 2 comments
Open

add a unique function #26

roosteracham opened this issue Apr 11, 2024 · 2 comments

Comments

@roosteracham
Copy link

In daily development, the Map, Filter, and Reduce functions provided by FP are indeed very useful, but there may be identical elements in the arrays or slices used in business, so I have to deduplicate the arrays. Because FP does not provide deduplication functionality, I can only use the closure function to deduplicate when writing the Map myself, which is not very convenient. So I wrote functions for array and slice deduplication.

@roosteracham
Copy link
Author

package fp

// Calls a defined by function on each element of an array, and returns an array with all element distinct.
func Unique[T any, K comparable](by func(T) K) func([]T) []T {

return func(xs []T) []T {
	result := make([]T, 0, len(xs))
	// unique map
	m := make(map[K]struct{}, len(xs))

	for _, item := range xs {
		key := by(item)
		if _, ok := m[key]; ok {
			continue
		}

		m[key] = struct{}{}
		result = append(result, item)
	}

	return result
}

}

@roosteracham
Copy link
Author

package fp

import (
"testing"

"github.com/repeale/fp-go/lambda"

)

func TestUnique(t *testing.T) {
// Test : get unique values

res := Unique(lambda.Identify[int])([]int{1, 2, 3, 3})

if len(res) != 3 {
	t.Error("Unique should return unique values")
}

}

func TestUnique2(t *testing.T) {
// Test : get unique values

res := Pipe3(
	Map(add1),
	Filter(func(x int) bool {
		return x % 2 == 0
	}),
	Unique(lambda.Identify[int]),
)([]int{1, 2, 3, 3})

if len(res) != 2 {
	t.Error("Unique should return unique values")
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant