Collection Package Documentation
Overview
The collection package provides a generic collection handling utility that implements common collection operations similar to those found in functional programming languages. It offers a fluent interface for manipulating slices of any type in Go using generics.
File Structure
The package consists of a single file:
collection.go
This file contains the entire implementation of the collection utility, providing various methods for collection manipulation.
Main Components
Collection Struct
type Collection[T any] struct {
Items []T
Original []T
}
- Generic structure that can hold any type of slice
- Maintains both current and original items
Key Functions
-
Basic Operations
New[T]: Creates a new collection instanceFirst(): Returns the first itemLast(): Returns the last itemLen(): Returns the collection length
-
Filtering and Mapping
Filter: Filters items based on a predicate functionMap: Transforms items using a mapping functionMapRef: Applies a function to each item by reference
-
Collection Manipulation
Include: Checks if an item exists in the collectionAddIfNotExists: Adds an item if it doesn't existSort: Sorts the collection using a custom comparatorUnique: Removes duplicates based on a key function
-
Utility Functions
HasSimilar: Checks if items are similar based on a comparison functionGetStringSlice: Converts collection items to string slice
Usage Example
collection := New([]int{1, 2, 3, 4, 5})
result := collection.
Filter(func(i int) bool { return i > 2 }).
Sort(func(a, b int) bool { return a < b }).
Items
Purpose
The package provides a convenient way to perform common collection operations with type safety using Go's generics feature. It's particularly useful for:
- Data transformation
- Filtering collections
- Sorting with custom logic
- Removing duplicates
- Chain operations on collections
This package simplifies collection manipulation tasks by providing a fluent interface and type-safe operations, making code more readable and maintainable.