slicesutils

package module
v0.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 28, 2025 License: MIT Imports: 5 Imported by: 2

README

slicesutils – Utility Functions for Slices in Go (Legacy)

A lightweight package providing utility functions for working with slices in Go, designed for versions prior to the introduction of the slices package in the standard library.

This package is considered legacy and is intended for projects that require backwards compatibility with earlier Go versions.

Some functions are still usefull in newer Go versions.

Examples

Max
import "bitbucket.org/yourteam/slicesutils"

max := slicesutils.Max(3, 1, 9, 5)
// max == 9
doubled := slicesutils.Map([]int{1, 2, 3}, func(n int) int {
    return n * 2
})
// doubled == []int{2, 4, 6}
Filter
evens := slicesutils.Filter([]int{1, 2, 3, 4}, func(n int) bool {
    return n%2 == 0
})
// evens == []int{2, 4}
Reduce
sum := slicesutils.Reduce([]int{1, 2, 3, 4}, func(acc, n int) int {
    return acc + n
}, 0)
// sum == 10
ParallelForEach
slicesutils.ParallelForEach([]string{"a", "b", "c"}, func(s string) {
    fmt.Println(s) // Some expensive operations
})
Chunk
chunks := slicesutils.Chunk([]int{1, 2, 3, 4, 5}, 2)
// chunks == [][]int{{1, 2}, {3, 4}, {5}}
Distinct
unique := slicesutils.Distinct([]int{1, 2, 2, 3, 3, 3})
// unique == []int{1, 2, 3}

Open Source and Contributions

This package is open source and maintained with the intention of being useful for the Go community, especially when working with legacy code or older Go versions. While some functions may overlap with newer standard packages, this library serves as a practical alternative and is open to improvement. Contributions, suggestions, and issue reports are all welcome!

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func All

func All[I any, S ~[]I](slice S, predicate func(I) bool) bool

All checks if all elements in the given slice satisfy the provided predicate function. It returns true if all elements satisfy the predicate, otherwise it returns false.

func Any

func Any[I any, S ~[]I](slice S, predicate func(I) bool) bool

Any checks if any element in the slice satisfies the given predicate function. It returns true if at least one element matches the predicate, otherwise false.

func Chunk

func Chunk[I any, S ~[]I](slice S, chunkSize int) []S

Chunk splits a slice into multiple smaller slices (chunks) of a specified size. If the chunkSize is less than or equal to 0, or if the input slice is empty, it returns an empty slice of slices.

The function uses generics to work with slices of any type.

Parameters:

  • slice: The input slice to be split into chunks.
  • chunkSize: The desired size of each chunk.

Returns:

A slice of slices, where each inner slice is a chunk of the original slice.

func Compare

func Compare[I comparable, S ~[]I](a, b S) bool

Compare takes two slices of any comparable type and returns true if they are equal. Two slices are considered equal if they have the same length and all corresponding elements are equal.

Returns true if the slices are equal, false otherwise.

func Contains

func Contains[I comparable, S ~[]I](slice S, element I) bool

Contains checks if the given element is present in the slice. It returns true if the element is found, otherwise it returns false.

func Difference

func Difference[I comparable, S ~[]I](a, b S) S

Difference returns the elements in slice `a` that are not in slice `b`. It uses a map to track the elements in `b` for efficient lookups.

Type Parameters:

T: a type that is comparable (supports the == and != operators).

Parameters:

a: the first slice of elements.
b: the second slice of elements.

Returns:

A slice containing the elements that are in `a` but not in `b`.

func Distinct

func Distinct[I comparable, S ~[]I](slice S) S

Distinct returns a new slice containing only the distinct elements from the input slice. The order of elements in the result slice is the same as their first occurrence in the input slice.

func Filter

func Filter[I any, S ~[]I](inputSlice S, filterFunc func(I) bool) S

Filter applies a filter function to each element in the inputSlice and returns a new slice containing only the elements for which the filter function returns true. The filter function takes an element of type T as input and returns a boolean value. The inputSlice is not modified.

func Find

func Find[I any, S ~[]I](inputSlice S, findFunc func(I) bool) (foundItem I, didFind bool)

Find searches for an element in the inputSlice that satisfies the given findFunc. It returns the first element that matches the condition or the zero value of type T if no match is found.

func FindIndex

func FindIndex[I any, S ~[]I](inputSlice S, findFunc func(I) bool) int

FindIndex returns the index of the first element in the inputSlice that satisfies the findFunc condition. If no element satisfies the condition, it returns -1.

func Intersection

func Intersection[I comparable, S ~[]I](a, b S) S

Intersection returns the common elements between two slices. It takes two slices of any comparable type and returns a slice containing the elements that are present in both input slices.

func Map

func Map[I any, O any, S ~[]I](inputSlice S, mapFunc func(I) O) []O

Map applies a mapping function to each element of the input slice and returns a new slice containing the results.

func Max

func Max(elements ...int) int

Max returns the maximum value in the provided slice. If no elements are provided, it panics with "No element provided to Max".

func ParallelForEach

func ParallelForEach[I any, S ~[]I](inputSlice S, forEachFunc func(I))

ParallelForEach applies a given function to each element of the input slice in parallel. The number of parallel workers is determined by the minimum of the number of CPU cores and the length of the input slice.

Type Parameters:

T: The type of elements in the input slice.

Parameters:

inputSlice: The slice of elements to process. If nil, the function returns immediately.
forEachFunc: The function to apply to each element of the input slice.

Example usage:

ParallelForEach([]int{1, 2, 3, 4}, func(n int) {
    fmt.Println(n)
})

func ParallelMap

func ParallelMap[I any, O any, S ~[]I](inputSlice S, mapFunc func(I) O) []O

ParallelMap applies the given map function concurrently to each element in the input slice. It creates a fixed number of worker goroutines to process the elements in parallel. The input slice is divided into chunks and each chunk is processed by a worker goroutine. The results are collected and returned as a new slice in the same order as the input. The map function takes an element of type T as input and returns an element of type U. The number of worker goroutines is determined by the number of available CPU cores. This function blocks until all worker goroutines have completed their tasks.

func Reduce

func Reduce[I any, O any, S ~[]I](inputSlice S, reduceFunc func(O, I) O, initialValue O) O

Reduce applies a function to each element of the input slice and returns a single value. The reduceFunc function takes two arguments: an accumulator value of type U and an element of the input slice of type I. It returns a new accumulator value of type O. The initialValue is the initial value of the accumulator. Reduce iterates over the inputSlice, applying the reduceFunc function to each element and the current accumulator value. The result of each iteration becomes the new accumulator value for the next iteration. Finally, the function returns the final accumulator value.

func RemoveElement

func RemoveElement[I comparable, S ~[]I](slice S, element I, occurrencesToDelete *int) S

RemoveElement removes the first n occurrences of the specified element from the given slice. Passing nil to occurrencesToDelete will remove all occurrences of the element. It returns a new slice with the element removed, or the original slice if the element is not found.

func RemoveElements

func RemoveElements[I comparable, S ~[]I](slice S, elements ...I) S

RemoveElements removes all occurrences of the specified elements from the given slice. It returns a new slice with the elements removed.

The function uses a map to keep track of the elements to be removed, ensuring efficient lookups.

func RemoveFirstOccurrence

func RemoveFirstOccurrence[I comparable, S ~[]I](slice S, element I) S

RemoveFirstOccurrence removes the first occurrence of the specified element from the given slice. It's a shorthand for calling RemoveElement with occurrencesToDelete set to 1.

func Reverse

func Reverse[I any, S ~[]I](slice S) S

func SafeExcecute

func SafeExcecute[T_out any](fn func() (T_out, error)) (output T_out, err error)

SafeExcecute executes a given function and recovers from any panic that occurs during its execution. It returns the output of the function and any error that occurred. If a panic occurs, it intercepts the panic and returns it as an error.

func SafeExcecuteWithStackTrace added in v0.1.3

func SafeExcecuteWithStackTrace[T_out any](fn func() (T_out, error)) (output T_out, err error)

SafeExcecuteWithStackTrace executes a function that returns a value and an error, and ensures that any panic during the execution is recovered and converted into an error with a stack trace.

func SafeFind

func SafeFind[I any, S ~[]I](inputSlice S, findFunc func(I) (bool, error)) (foundItem I, didFind bool, err error)

SafeFind iterates over the elements of the input slice and applies the provided findFunc to each element to determine if it matches a specific condition. If a match is found, the function returns the matching item, a boolean indicating success, and nil for the error. If no match is found, it returns the zero value of the item type, false, and nil for the error. If an error occurs during the execution of findFunc, the function immediately returns the zero value of the item type, false, and the encountered error.

func SafeMap

func SafeMap[I any, O any, S ~[]I](inputSlice S, mappingFunc func(I) (O, error)) ([]O, error)

SafeMap applies a mapping function to each element of an input slice, returning a new slice with the results. If the mapping function returns an error for any element or panics, SafeMap will return that error and halt further processing.

func SafeReduce

func SafeReduce[I any, O any, S ~[]I](inputSlice S, reduceFunc func(O, I) (O, error), initialValue O) (O, error)

SafeReduce is a generic function that safely reduces a slice of input elements into a single output value by applying a user-defined reduce function. It ensures that if an error is encountered during the reduction process, the reduce stops and returns the error.

func Sort

func Sort[I any, S ~[]I](slice S, less func(i, j I) bool) S

Sort sorts a slice of any type in place based on the provided less function. The less function should return true if the first argument is considered to be less than the second.

func Union

func Union[I comparable, S ~[]I](a, b S) S

Union returns the union of two slices, removing duplicate elements. The function takes two slices of any comparable type and returns a new slice containing all unique elements from both input slices.

Example usage:

a := []int{1, 2, 3}
b := []int{3, 4, 5}
result := Union(a, b) // result will be []int{1, 2, 3, 4, 5}

The order of elements in the resulting slice is not guaranteed.

func UniqueItemsById

func UniqueItemsById[Id comparable, I identifiable[Id], S ~[]I](slice S) S

UniqueItemsById returns a slice containing only the unique items from the input slice, where uniqueness is determined by the item's Id. The function uses a map to track seen Ids and filters out duplicates. Items should implement the identifiable interface. Thus they must have a method Id() that returns a unique identifier.

func WeightedSort

func WeightedSort[I any, W cmp.Ordered, S ~[]I](slice S, getWeighfn func(I) W, less func(i, j I) bool) S

WeightedSort sorts a slice of any type based on a weight function and a less function. The weight function determines the primary sorting order by returning an integer weight for each element. The less function is used as a secondary sorting order when two elements have the same weight.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL