Skip to main content

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

  1. Basic Operations

    • New[T]: Creates a new collection instance
    • First(): Returns the first item
    • Last(): Returns the last item
    • Len(): Returns the collection length
  2. Filtering and Mapping

    • Filter: Filters items based on a predicate function
    • Map: Transforms items using a mapping function
    • MapRef: Applies a function to each item by reference
  3. Collection Manipulation

    • Include: Checks if an item exists in the collection
    • AddIfNotExists: Adds an item if it doesn't exist
    • Sort: Sorts the collection using a custom comparator
    • Unique: Removes duplicates based on a key function
  4. Utility Functions

    • HasSimilar: Checks if items are similar based on a comparison function
    • GetStringSlice: 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.