collection

package module
v1.0.12 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2024 License: MIT Imports: 7 Imported by: 0

README

Collections

godoc license Build Status Go Coverage

Collections is a Go package that provides an extensive collection of utility functions and a thread-safe map for working with collections. It includes a variety of functions such as filtering, mapping, sorting, and merging, as well as methods for accessing and modifying a map concurrently. Install the package with a simple go get command and import it into your project. Get started with the list of functions provided and streamline your collection-based workloads today!

Installation

To install this package, run the following command:

go get github.com/sergeydobrodey/collection

Usage

import "github.com/sergeydobrodey/collection"
Documentation

Documentation is hosted at https://pkg.go.dev/github.com/sergeydobrodey/collection.

Examples
Slice transformations
package main

import (
	"fmt"

	"github.com/sergeydobrodey/collection"
)

type User struct {
	id   uint
	name string
}

func (u User) ID() uint {
	return u.id
}

func (u User) Name() string {
	return u.name
}

func main() {
	var users = []User{{0, "Rob"}, {1, "Ken"}}

	var names = collection.TransformBy(users, User.Name)
	fmt.Println(names)
	// Output: [Rob Ken]

	var usersByID = collection.SliceToMap(users, User.ID)
	fmt.Println(usersByID)
	// Output: map[0:{0 Rob} 1:{1 Ken}]
}
Channels aggregation
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/sergeydobrodey/collection"
)

type Worker interface {
	Run(context.Context)
	Done() <-chan struct{}
}

func NewWorker() Worker {
	return &worker{
		done: make(chan struct{}),
	}
}

type worker struct {
	done chan struct{}
}

func (w *worker) Done() <-chan struct{} {
	return w.done
}

func (w *worker) Run(ctx context.Context) {
	defer close(w.done)

	<-ctx.Done()
}

func main() {
	var ctx, cancel = context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	var worker1 = NewWorker()
	go worker1.Run(ctx)

	var worker2 = NewWorker()
	go worker2.Run(ctx)

	var allWorkersDone = collection.ChannelsMerge(worker1.Done(), worker2.Done())
	<-allWorkersDone

	fmt.Println("all workers finished")
}
Collection Functions

This package provides several functions for working with collections:

  • Aggregate[T, K any](source []T, aggregator func(K, T) K) K
  • All[T any](source []T, predicate func(T) bool) bool
  • Any[T any](source []T, predicate func(T) bool) bool
  • AsyncTransformBy[T, K any](source []T, transform func(T) K) []K
  • AsyncTryTransformBy[T, K any](parent context.Context, source []T, transform func(context.Context, T) (K, error)) ([]K, error)
  • ChannelsMerge[T any](args ...<-chan T) <-chan T
  • ChannelsReadonly[T any](args ...chan T) []<-chan T
  • Contains[T comparable](source []T, item T) bool
  • Copy[T any](source []T) []T
  • Difference[T comparable](a []T, b []T) []T
  • Distinct[T comparable](source []T) []T
  • DistinctBy[T any](source []T, equals func(left T, right T) bool) []T
  • Duplicates[T comparable](source []T) []T
  • Each[T any](source []T, do func(T))
  • Equal[T ~[]E, E comparable](s1, s2 T) bool
  • FilterBy[T any](source []T, filter Filter[T]) []T
  • Filter[T any] func(T) bool
  • Flatten[T any](source [][]T) []T
  • GroupBy[T any, K comparable](source []T, keyFunc func(T) K) map[K][]T
  • InFilter[T comparable](source []T, present bool) Filter[T]
  • Intersection[T comparable](a []T, b []T) []T
  • MapContains[K comparable, T any](source map[K]T, item K) bool
  • MapEach[K comparable, T any](source map[K]T, do func(key K, value T))
  • MapEqual[M1, M2 ~map[K]V, K, V comparable](m1 M1, m2 M2) bool
  • MapFilterBy[K comparable, T any](source map[K]T, filter func(key K, value T) bool) map[K]T
  • MapKeys[K comparable, T any](source map[K]T) []K
  • MapToSlice[K comparable, T1 any, T2 any](source map[K]T1, transform func(key K, value T1) T2) []T2
  • MapTransformBy[K comparable, T1, T2 any](source map[K]T1, transform func(T1) T2) map[K]T2
  • MapValues[K comparable, T any](source map[K]T) []T
  • MaxOf[T constraints.Ordered](elements ...T) T
  • Max[T constraints.Ordered](l T, r T) T
  • ChannelsMerge[T any](args ...<-chan T) <-chan T
  • ChannelsReadonly[T any](args ...chan T) []<-chan T
  • MinOf[T constraints.Ordered](elements ...T) T
  • Min[T constraints.Ordered](l T, r T) T
  • Reverse[T any](source []T)
  • SliceToMap[K comparable, T any](source []T, keyFunc func(T) K) map[K]T
  • SortBy[T any](source []T, less func(l T, r T) bool)
  • Sort[T constraints.Ordered](source []T)
  • TransformBy[T, K any](source []T, transform func(T) K) []K
  • TransformManyBy[T, K any](source []T, transform func(T) []K) []K
  • TryTransformBy[T, K any](source []T, transform func(T) (K, error)) ([]K, error)
  • TryMapTransformBy[K comparable, T1, T2 any](source map[K]T1, transform func(T1) (T2, error)) (map[K]T2, error)
SyncMap

The SyncMap type is a thread-safe map that can be accessed concurrently. It provides the following methods:

  • CompareAndDelete(key K, old V) (deleted bool)
  • CompareAndSwap(key K, old V, new V) bool
  • Delete(key K)
  • Load(key K) (value V, ok bool)
  • LoadAndDelete(key K) (value V, loaded bool)
  • LoadOrStore(key K, value V) (actual V, loaded bool)
  • Range(f func(key K, value V) bool)
  • Store(key K, value V)
  • Swap(key K, value V) (previous V, loaded bool)

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Aggregate

func Aggregate[T, K any](source []T, aggregator func(K, T) K) K

Aggregate aggregates the elements of the slice into a single value using a user-defined aggregator function.

Example

ExampleAggregate: Example function demonstrating the use of the Aggregate function.

package main

import (
	"fmt"

	"github.com/sergeydobrodey/collection"
)

func main() {
	sum := func(s int, v int) int { return s + v }

	result := collection.Aggregate([]int{1, 2, 3, 4, 5}, sum)
	fmt.Println(result)
}
Output:

15

func All added in v1.0.6

func All[T any](source []T, predicate func(T) bool) bool

All: Returns true if every element in the slice satisfies the given predicate function.

func Any

func Any[T any](source []T, predicate func(T) bool) bool

Any: Returns true if at least one element in the slice satisfies the given predicate function.

func AsyncTransformBy added in v1.0.11

func AsyncTransformBy[T, K any](source []T, transform func(T) K) []K

AsyncTransformBy async transform the source slice of type T to a new slice of type K using the provided transform function.

func AsyncTryTransformBy added in v1.0.8

func AsyncTryTransformBy[T, K any](parent context.Context, source []T, transform func(context.Context, T) (K, error)) ([]K, error)

AsyncTryTransformBy tries to async transform the source slice of type T to a new slice of type K using the provided transform function.

func ChannelsMerge added in v1.0.1

func ChannelsMerge[T any](args ...<-chan T) <-chan T

ChannelsMerge merge input from N channels to 1 receive only channel

func ChannelsReadonly added in v1.0.1

func ChannelsReadonly[T any](args ...chan T) []<-chan T

ChannelsReadonly transforms input N channels to receive only channels

func Contains

func Contains[T comparable](source []T, item T) bool

Contains returns true if the given item is present in the slice.

func Copy added in v1.0.3

func Copy[T any](source []T) []T

Copy returns copy of the slice

func Difference

func Difference[T comparable](a []T, b []T) []T

Difference finds a set difference between a and b (values that are in a but not in b or a-b).

func Distinct

func Distinct[T comparable](source []T) []T

Distinct returns a new slice with all duplicate elements removed.

func DistinctBy added in v1.0.4

func DistinctBy[T any](source []T, equals func(left T, right T) bool) []T

DistinctBy returns a new slice with all duplicate elements removed.

func Duplicates

func Duplicates[T comparable](source []T) []T

Duplicates returns a new slice with all elements that appear more than once in the original slice.

func Each

func Each[T any](source []T, do func(T))

Each calls the given function for each element in the slice.

func Equal added in v1.0.5

func Equal[T ~[]E, E comparable](s1, s2 T) bool

Equal is equal to slices.Equal

func FilterBy

func FilterBy[T any](source []T, filter Filter[T]) []T

FilterBy returns a new slice with only the elements that satisfy the given filter function.

func Flatten

func Flatten[T any](source [][]T) []T

Flatten flattens a slice of slices into a single slice.

func GroupBy

func GroupBy[T any, K comparable](source []T, keyFunc func(T) K) map[K][]T

GroupBy groups the elements of the slice by a key returned by the given key function.

func Intersection

func Intersection[T comparable](a []T, b []T) []T

Intersection finds a set intersection between a and b (unique values that are in a and in b).

func MapContains

func MapContains[K comparable, T any](source map[K]T, item K) bool

MapContains returns true if the given key is present in the map.

func MapEach

func MapEach[K comparable, T any](source map[K]T, do func(key K, value T))

MapEach calls the given function for each key-value pair in the map.

func MapEqual added in v1.0.5

func MapEqual[M1, M2 ~map[K]V, K, V comparable](m1 M1, m2 M2) bool

MapEqual is equal to maps.Equal

func MapFilterBy

func MapFilterBy[K comparable, T any](source map[K]T, filter func(key K, value T) bool) map[K]T

MapFilterBy returns a new map with only the key-value pairs that satisfy the given filter function.

func MapKeys

func MapKeys[K comparable, T any](source map[K]T) []K

MapKeys returns a new slice containing all keys in the map.

func MapToSlice

func MapToSlice[K comparable, T1 any, T2 any](source map[K]T1, transform func(key K, value T1) T2) []T2

MapToSlice convert the source map of type T1 to a slice of type T2 using the provided transform function on each key-value pair.

func MapTransformBy

func MapTransformBy[K comparable, T1, T2 any](source map[K]T1, transform func(T1) T2) map[K]T2

MapTransformBy transform the values of the source map of type T1 to a new map of type T2 using the provided transform function.

func MapValues

func MapValues[K comparable, T any](source map[K]T) []T

MapValues returns a slice of type T containing the values of the source map of type T, ordered by key.

func Max

func Max[T constraints.Ordered](l T, r T) T

Max returns the larger of x or y.

func MaxOf

func MaxOf[T constraints.Ordered](elements ...T) T

MaxOf returns the largest value among the provided elements or zero value

func Min

func Min[T constraints.Ordered](l T, r T) T

Min returns the smaller of x or y.

func MinOf

func MinOf[T constraints.Ordered](elements ...T) T

MinOf returns the smallest value among the provided elements or zero value

func Reverse

func Reverse[T any](source []T)

Reverse reverses the order of the elements in the source slice of type T.

func SliceToMap

func SliceToMap[K comparable, T any](source []T, keyFunc func(T) K) map[K]T

SliceToMap convert the source slice of type T to a new map of type T with keys generated by the provided keyFunc.

func Sort

func Sort[T constraints.Ordered](source []T)

Sort sorts the source slice of type T in ascending order.

func SortBy

func SortBy[T any](source []T, less func(l T, r T) bool)

SortBy sorts the source slice of type T according to the less function provided.

func TransformBy

func TransformBy[T, K any](source []T, transform func(T) K) []K

TransformBy transform the source slice of type T to a new slice of type K using the provided transform function.

func TransformManyBy

func TransformManyBy[T, K any](source []T, transform func(T) []K) []K

TransformManyBy transforms the source slice of type T to multiple slices of type K using the provided transform function.

func TryMapTransformBy added in v1.0.7

func TryMapTransformBy[K comparable, T1, T2 any](source map[K]T1, transform func(T1) (T2, error)) (map[K]T2, error)

TryMapTransformBy attempts to transform the values of the source map of type T1 to a new map of type T2 using the provided transform function.

func TryTransformBy added in v1.0.3

func TryTransformBy[T, K any](source []T, transform func(T) (K, error)) ([]K, error)

TryTransformBy tries to transform the source slice of type T to a new slice of type K using the provided transform function.

Types

type Filter

type Filter[T any] func(T) bool

func InFilter

func InFilter[T comparable](source []T, present bool) Filter[T]

InFilter returns a filter function that filters elements based on whether they are present or absent in the given slice.

type KV

type KV[K comparable, T any] struct {
	Key   K
	Value T
}

type Pair added in v1.0.8

type Pair[T any, V any] struct {
	First  T
	Second V
}

type SafeMap added in v1.0.12

type SafeMap[K comparable, V any] struct {
	// contains filtered or unexported fields
}

func NewSafeMap added in v1.0.12

func NewSafeMap[K comparable, V any]() *SafeMap[K, V]

func (*SafeMap[K, V]) Clear added in v1.0.12

func (s *SafeMap[K, V]) Clear()

func (*SafeMap[K, V]) Delete added in v1.0.12

func (s *SafeMap[K, V]) Delete(key K)

func (*SafeMap[K, V]) ForEach added in v1.0.12

func (s *SafeMap[K, V]) ForEach(fn func(K, V))

func (*SafeMap[K, V]) Get added in v1.0.12

func (s *SafeMap[K, V]) Get(key K) (v V, ok bool)

func (*SafeMap[K, V]) Has added in v1.0.12

func (s *SafeMap[K, V]) Has(key K) bool

func (*SafeMap[K, V]) Keys added in v1.0.12

func (s *SafeMap[K, V]) Keys() []K

func (*SafeMap[K, V]) Len added in v1.0.12

func (s *SafeMap[K, V]) Len() int

func (*SafeMap[K, V]) Set added in v1.0.12

func (s *SafeMap[K, V]) Set(key K, value V)

func (*SafeMap[K, V]) Values added in v1.0.12

func (s *SafeMap[K, V]) Values() []V

type SyncMap

type SyncMap[K comparable, V any] struct {
	// contains filtered or unexported fields
}

func (*SyncMap[K, V]) CompareAndDelete

func (m *SyncMap[K, V]) CompareAndDelete(key K, old V) (deleted bool)

CompareAndDelete deletes the entry for key if its value is equal to old. The old value must be of a comparable type.

func (*SyncMap[K, V]) CompareAndSwap

func (m *SyncMap[K, V]) CompareAndSwap(key K, old V, new V) bool

CompareAndSwap swaps the old and new values for key if the value stored in the map is equal to old. The old value must be of a comparable type.

func (*SyncMap[K, V]) Delete

func (m *SyncMap[K, V]) Delete(key K)

Delete deletes the value for a key.

func (*SyncMap[K, V]) Load

func (m *SyncMap[K, V]) Load(key K) (value V, ok bool)

Load returns the value stored in the map for a key, or zero value if no value is present. The ok result indicates whether value was found in the map.

func (*SyncMap[K, V]) LoadAndDelete

func (m *SyncMap[K, V]) LoadAndDelete(key K) (value V, loaded bool)

LoadAndDelete deletes the value for a key, returning the previous value if any. The loaded result reports whether the key was present.

func (*SyncMap[K, V]) LoadOrStore

func (m *SyncMap[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool)

LoadOrStore returns the existing value for the key if present. Otherwise, it stores and returns the given value. The loaded result is true if the value was loaded, false if stored.

func (*SyncMap[K, V]) Range

func (m *SyncMap[K, V]) Range(f func(key K, value V) bool)

Range calls f sequentially for each key and value present in the map. If f returns false, range stops the iteration. Read sync.Map Range for more details

func (*SyncMap[K, V]) Store

func (m *SyncMap[K, V]) Store(key K, value V)

Store sets the value for a key.

func (*SyncMap[K, V]) Swap

func (m *SyncMap[K, V]) Swap(key K, value V) (previous V, loaded bool)

Swap swaps the value for a key and returns the previous value if any. The loaded result reports whether the key was present.

Jump to

Keyboard shortcuts

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