# README
arrayOperations
Small utility library for performing common operations on slices in golang.
I don't promise that these are optimized (not even close!), but they work :)
Quickstart
var a = []int{1, 1, 2, 3}
var b = []int{2, 4}
diff := Difference[int](a, b)
// []int{1, 3}
fmt.Println(diff)
API
FindOne[T any](arr []T, guard func(T) bool) (T, bool)
Reduce[T, A any](arr []T, fn func(A, T) A, init A) A
Filter[T any](arr []T, guard func(T) bool) []T
Map[T any](arr []T, transform func(T) T) []T
Distinct[T comparable](arrs ...[]T) []T
Intersect[T comparable](arrs ...[]T) []T
Union[T comparable](arrs ...[]T) []T
Difference[T comparable](arrs ...[]T) []T
Docs
Docs are available, here
License
MIT
# Functions
Difference returns a slice of values that are only present in one of the input slices
// example #1 a := []int{1, 2, 2, 4, 6} b := []int{2, 4, 5} fmt.Println(Difference[int](a, b)) // output: []int{1, 5, 6}
// example #2 fmt.Println(Difference[int]([]int{1, 1, 3, 4, 5, 6})) // output: []int{1, 3, 4, 5, 6}.
Distinct returns the unique vals of a slice
fmt.Println(Distinct[int]([]int{1, 1, 2, 3})) // output: [1, 2, 3].
Filter iterates through an array applying the guard function to each element and returns the elements that pass
arr := []int{0,1,2,3,4} func isEven(i int) bool { return i % 2 == 0 } fmt.Println(Filter[int](arr, isEven)) // output: [0,2,4].
FindOne iterates through an array applying the guard function to each element and returns the first element that passes.
Intersect returns a slice of values that are present in all of the input slices
// example #1 a := []int{1, 1, 3, 4, 5, 6} b := []int{2, 3, 6} fmt.Println(Intersect[int](a, b)) // output: []int{3, 6}
// example #2 fmt.Println(Intersect[int]([]int{1, 1, 3, 4, 5, 6})) // output: []int{1, 3, 4, 5, 6}.
Map iterates through an array applying the transform function to each element and returns the modified array
arr := []int{1,2,3} func addTen(i int) int { return i + 10 } fmt.Println(Map[int](arr, addTen)) // output: [11, 12, 13].
Reduce iterates through an array applying the function to each element and the cumulative value and the final state of the cumulative value
arr := []string{"cat","dog","cat","cow"} func countAnimals(state map[string]int, animal string) map[string]int { count, ok := state[animal] if !ok { state[animal] = 0 return state }
state[animal] = count + 1 return state } initialState := make(map[string]int) fmt.Println(Reduce[string, map[string]int](arr, countAnimals, initialState)) // output: map["cat":2 "dog":1 "cow":1].
Union returns a slice that contains the unique values of all the input slices
// example #1 a := []int{1, 2, 2, 4, 6} b := []int{2, 4, 5} fmt.Println(Union[int](a, b)) // output: []int{1, 2, 4, 5, 6}
// example #2 fmt.Println(Union[int]([]int{1, 1, 3, 4, 5, 6})) // output: []int{1, 3, 4, 5, 6}.