Skip to content

SliceUtils provides several high-level functions for interacting with slices while increasing code readability.

License

Notifications You must be signed in to change notification settings

kauppie/sliceutils

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

47 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SliceUtils | Slice Utility Functions

CI status Go Report Card codecov MIT

This library implements several high-level functions useful for interacting with slices. It reduces boilerplate required by for-loops and variable initializations.

Library takes advantage of Go generics increasing usability by compile-time type-safety. Go version of at least 1.18 is therefore required.

Examples

Below are few examples on how this library can make your code more concise and less error-prone.

Map strings to their lengths

var strings []string

// Replace
lens := make([]int, 0)
for _, s := range strings {
  lens = append(lens, len(s))
}

// With
lens := Map(strings, func(s string) int { return len(s) })

Get positive numbers from a slice

var nums []int

// Replace
pos := make([]int, 0)
for _, n := range nums {
  if n > 0 {
    pos = append(pos, n)
  }
}

// With
pos := Filter(nums, func(n int) bool { return n > 0 })

Flatten slice

var slices [][]int

// Replace
flat := make([]int, 0)
for _, slice := range slices {
  flat = append(flat, slice...)
}

// With
flat := Flatten(slices)

Deduplicate slice

var slice []int

// Replace
uniques := make(map[int]struct{})
dedup := make([]int, 0)
for _, val := range slice {
  if _, ok := uniques[val]; !ok {
    dedup = append(dedup, val)
    uniques[val] = struct{}{}
  }
}

// With
dedup := Deduplicate(slice)

List of functions

>> All

Returns true if all slice elements are evaluated true with given argument function.

>> Any

Returns true if any slice element is evaluated true with given argument function.

>> AreDisjoint

Returns true if two slice sets do not have common elements.

>> Contains

Returns true if slice contains given element.

>> Count

Counts the number of elements in a slice for which the argument function returns true.

>> Deduplicate

Removes duplicate elements from a slice creating a new slice.

>> DeduplicateInPlace

Removes duplicate elements from a slice in place.

>> Difference

Calculates a difference set between two slice sets.

>> Filter

Creates a slice which contains slice elements for which the argument function returns true.

>> FilterInPlace

Retains elements in a slice for which the argument function returns true. Modifies the original slice and therefore does not allocate.

>> FilterMap

Filters and maps slice elements to new slice. See Filter and Map for more details. This function exists to allow better performance than using Filter and Map separately.

>> FindBy

Searches to find element's index in a slice for which the argument function returns true.

>> Flatten

Converts a N-dimensional slice into a N-1 -dimensional slice.

>> Fold

Folds a slice into a single value. Other name for such a function is reduce.

It starts with a initial value and updates it iteratively using the argument function and slice's elements to accumulate the final result.

>> Frequencies

Counts the number of occurrences for each element. Requires slice elements to be comparable.

>> Generate

Generates a slice of the given length. Slice elements are generated using the provided argument function.

>> Intersection

Calculates a intersection set between two slice sets.

>> IsSet

Returns true for slices that are sets i.e. contain only unique elements. Requires slice elements to be comparable.

>> IsSortedBy

Returns true for slices whose elements are sorted according to passed argument function.

>> IsSubSet

Returns true if first slice set is a subset of the second slice set.

>> IsSuperSet

Returns true if first slice set is a superset of the second slice set.

>> Join

Joins one or more slices together. Similar to Flatten but uses variadic arguments instead.

>> Map

Maps each element through argument function which can modify their type and/or value.

>> MapInPlace

Maps each slice element to a new value of the same type with provided mapping function. Does the operation in place modifying the original slice.

>> MaxBy

Returns the maximum element value in a slice using provided comparison function.

>> MinBy

Returns the minimum element value in a slice using provided comparison function.

>> Partition

Partitions slice elements into two separate slices by argument function's boolean return value.

>> PartitionInPlace

Partitions a slice in place so that the first partition contains elements for which the argument function return true, and the second partition contains elements that the function returns false for.

>> Reverse

Creates a slice where the order of elements are reversed.

>> ReverseInPlace

Reverses the order of elements in a slice.

>> SymmetricDifference

Calculates a symmetric difference set from two slice sets.

>> Union

Calculates a union set from two slice sets.

List of parallel functions

>> ParMap

Maps each element through argument function which can modify their type and/or value. Evenly distributes the mapping operation to multiple goroutines. The number of used goroutines is equal to the available number of logical processors.

Performance

Currently all the functions have at most O(n * m) time complexity, where n is length of the argument slice and m is time complexity of the argument function. Functions without argument functions have time complexity of at most O(n).

Performance over traditional for-loops is not yet tested.

About

SliceUtils provides several high-level functions for interacting with slices while increasing code readability.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages