From f7ab541d0a5ba5fe1701de7da8c356b634aaa4ff Mon Sep 17 00:00:00 2001 From: Timon Ringwald Date: Thu, 18 Aug 2022 13:41:16 +0200 Subject: [PATCH] initial commit --- comparator.go | 7 +++++++ go.mod | 5 +++++ go.sum | 2 ++ slices.go | 52 +++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 66 insertions(+) create mode 100644 comparator.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 slices.go diff --git a/comparator.go b/comparator.go new file mode 100644 index 0000000..a648866 --- /dev/null +++ b/comparator.go @@ -0,0 +1,7 @@ +package slices + +type EqualityComparator[T comparable] func(a, b T) bool + +func DefaultEqualityComparator[T comparable](a, b T) bool { + return a == b +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..52ff837 --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module git.milar.in/milarin/slices + +go 1.19 + +require git.milar.in/milarin/channel v0.0.7 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..e592c3c --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +git.milar.in/milarin/channel v0.0.7 h1:cVKtwgH/EE7U+XTHcoFCClJ4LR349KanzjX9xKwRcNg= +git.milar.in/milarin/channel v0.0.7/go.mod h1:We83LTI8S7u7II3pD+A2ChCDWJfCkcBUCUqii9HjTtM= diff --git a/slices.go b/slices.go new file mode 100644 index 0000000..171b184 --- /dev/null +++ b/slices.go @@ -0,0 +1,52 @@ +package slices + +import ( + "git.milar.in/milarin/channel" +) + +func IndexOf[T comparable](slice []T, value T) int { + return IndexOfCmp(slice, value, DefaultEqualityComparator[T]) +} + +func IndexOfCmp[T comparable](slice []T, value T, cmp EqualityComparator[T]) int { + for i, v := range slice { + if cmp(v, value) { + return i + } + } + return -1 +} + +func Contains[T comparable](slice []T, value T) bool { + return ContainsCmp(slice, value, DefaultEqualityComparator[T]) +} + +func ContainsCmp[T comparable](slice []T, value T, cmp EqualityComparator[T]) bool { + return IndexOfCmp(slice, value, cmp) != -1 +} + +func Map[I, O any](slice []I, mapper func(I) O) []O { + ret := make([]O, 0, len(slice)) + for _, v := range slice { + ret = append(ret, mapper(v)) + } + return ret +} + +func MapParallel[I, O any](slice []I, mapper func(I) O) []O { + return channel.ToSlice(channel.Map(channel.Of(slice...), mapper)) +} + +func MapParallelWithRunner[I, O any](slice []I, runner channel.Runner, mapper func(I) O) []O { + return channel.ToSlice(channel.MapWithRunner(channel.Of(slice...), runner, mapper)) +} + +func Each[T any](slice []T, f func(T)) { + EachIndex(slice, func(_ int, v T) { f(v) }) +} + +func EachIndex[T any](slice []T, f func(int, T)) { + for i, v := range slice { + f(i, v) + } +}