algo

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Dec 31, 2024 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package algo provides a fluent API for chaining data operations and algorithms. It enables building data processing pipelines with a clean, chainable interface.

Example usage:

pipeline := NewPipeline[int]().
    Filter(func(x int) bool { return x > 0 }).
    Map(func(x int) int { return x * 2 }).
    QuickSort(func(a, b int) bool { return a < b })

result, err := pipeline.Execute()

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BinarySearchOperation

type BinarySearchOperation[T any] struct {
	Predicate  func(T) bool
	FoundIndex int
}

BinarySearchOperation performs a binary search on sorted data. It requires the data to be sorted according to the predicate function's ordering.

func (*BinarySearchOperation[T]) Apply

func (b *BinarySearchOperation[T]) Apply(data []T) ([]T, error)

Apply performs the binary search operation on the data. It returns the original data slice and an error if the target is not found. The operation expects the data to be pre-sorted for correct results.

Example:

pipeline := NewPipeline[int]().
    QuickSort(func(a, b int) bool { return a < b }).
    BinarySearch(func(a int) bool { return a == 42 })
result, err := pipeline.Execute()

func (*BinarySearchOperation[T]) GetFoundIndex

func (b *BinarySearchOperation[T]) GetFoundIndex() int

GetFoundIndex returns the index of the found element after a successful binary search. Returns -1 if the element was not found or if the search has not been executed.

type DistinctOperation

type DistinctOperation[T any] struct {
	Equal func(a, b T) bool
}

DistinctOperation removes duplicate items from the data based on the provided equality function. It preserves the order of first occurrence of each unique item.

func (*DistinctOperation[T]) Apply

func (d *DistinctOperation[T]) Apply(data []T) ([]T, error)

Apply performs the distinct operation on the data. It returns a new slice containing only unique elements based on the Equal function.

Example:

pipeline := NewPipeline[Item]().
    Distinct(func(a, b Item) bool { return a.ID == b.ID })
result, err := pipeline.Execute()

type FilterOperation

type FilterOperation[T any] struct {
	Predicate func(T) bool
}

FilterOperation filters items in a slice based on a predicate function. It preserves the order of items that match the predicate.

func (*FilterOperation[T]) Apply

func (f *FilterOperation[T]) Apply(data []T) ([]T, error)

Apply performs the filter operation on the data. It returns a new slice containing only the elements that satisfy the predicate.

Example:

pipeline := NewPipeline[User]().
    Filter(func(u User) bool { return u.Age >= 18 })
result, err := pipeline.Execute()

type FindOperation

type FindOperation[T any] struct {
	Predicate func(T) bool
}

FindOperation locates items in a slice that match a predicate function. It returns all matching elements while preserving their original order.

func (*FindOperation[T]) Apply

func (f *FindOperation[T]) Apply(data []T) ([]T, error)

Apply performs the find operation on the data. It returns a new slice containing all elements that match the predicate.

Example:

pipeline := NewPipeline[Product]().
    Find(func(p Product) bool { return p.Category == "Electronics" })
result, err := pipeline.Execute()

type GroupedItem

type GroupedItem[K comparable, T any] struct {
	Key   K
	Items []T
}

GroupedItem represents a group of items sharing the same key.

func GroupBy

func GroupBy[T any, K comparable](data []T, keyFunc func(T) K) []GroupedItem[K, T]

GroupBy organizes items into groups based on a key function. Items with the same key are collected into the same group while maintaining their order.

Example:

orders := []Order{
    {ID: 1, UserID: 100, Item: "Book"},
    {ID: 2, UserID: 101, Item: "Pen"},
    {ID: 3, UserID: 100, Item: "Paper"},
}

groups := GroupBy(orders, func(o Order) int { return o.UserID })
// Results in groups by UserID: [100: [Order{1}, Order{3}], 101: [Order{2}]]

type HeapSortOperation

type HeapSortOperation[T any] struct {
	Comparator func(a, b T) bool
}

HeapSortOperation sorts data using the heap sort algorithm. It provides stable sorting with O(n log n) time complexity.

func (*HeapSortOperation[T]) Apply

func (h *HeapSortOperation[T]) Apply(data []T) ([]T, error)

Apply performs the heap sort operation on the data. It sorts the data in-place based on the provided comparator function.

Example:

pipeline := NewPipeline[int]().
    HeapSort(func(a, b int) bool { return a < b })
result, err := pipeline.Execute()

type Item

type Item struct {
	ID     int
	Name   string
	Active bool
}

Item is a common type used for testing.

type LinearSearchOperation

type LinearSearchOperation[T any] struct {
	Predicate func(T) bool
}

LinearSearchOperation performs a sequential search through the data. It searches for elements that match the given predicate function.

func (*LinearSearchOperation[T]) Apply

func (l *LinearSearchOperation[T]) Apply(data []T) ([]T, error)

Apply performs the linear search operation on the data. It returns the data and an error if no matching element is found.

Example:

pipeline := NewPipeline[Product]().
    LinearSearch(func(p Product) bool { return p.SKU == "ABC123" })
result, err := pipeline.Execute()

type MapOperation

type MapOperation[T any] struct {
	Mapper func(T) T
}

MapOperation transforms each element in the data using a mapping function. The transformation is applied to all elements while preserving their order.

func (*MapOperation[T]) Apply

func (m *MapOperation[T]) Apply(data []T) ([]T, error)

Apply performs the map operation on the data. It returns a new slice containing the transformed elements.

Example:

pipeline := NewPipeline[int]().
    Map(func(x int) int { return x * 2 })
result, err := pipeline.Execute()

type MergeSortOperation

type MergeSortOperation[T any] struct {
	Comparator func(a, b T) bool
}

MergeSortOperation sorts data using the merge sort algorithm. It provides stable sorting with O(n log n) time complexity and uses O(n) additional space.

func (*MergeSortOperation[T]) Apply

func (m *MergeSortOperation[T]) Apply(data []T) ([]T, error)

Apply performs the merge sort operation on the data. It returns a sorted slice based on the provided comparator function.

Example:

pipeline := NewPipeline[float64]().
    MergeSort(func(a, b float64) bool { return a < b })
result, err := pipeline.Execute()

type Operation

type Operation[T comparable] interface {
	Apply(data []T) ([]T, error)
}

Operation defines the interface for all pipeline operations. Each operation implements Apply to transform or process the data.

type Order

type Order struct {
	OrderID int
	UserID  int
	Item    string
}

Order is another common type used for testing.

type Pipeline

type Pipeline[T comparable] struct {
	// contains filtered or unexported fields
}

Pipeline represents a sequence of operations to be performed on data. Operations are executed in the order they were added to the pipeline.

func NewPipeline

func NewPipeline[T comparable]() *Pipeline[T]

NewPipeline creates a new Pipeline instance.

Example:

pipeline := NewPipeline[User]()

func NewPipelineWithData

func NewPipelineWithData[T comparable](data []T) *Pipeline[T]

NewPipelineWithData creates a new Pipeline instance with initial data.

Example:

data := []int{1, 2, 3, 4, 5}
pipeline := NewPipelineWithData(data).
	Filter(func(x int) bool { return x > 2 }).
	Map(func(x int) int { return x * 2 }).
	QuickSort(func(a, b int) bool { return a < b })

result, err := pipeline.Execute()

func (*Pipeline[T]) AddOperation

func (p *Pipeline[T]) AddOperation(op Operation[T]) *Pipeline[T]

AddOperation adds an operation to the pipeline. Returns the pipeline for method chaining.

func (*Pipeline[T]) BinarySearch

func (p *Pipeline[T]) BinarySearch(predicate func(T) bool) *Pipeline[T]

BinarySearch adds a binary search operation to the pipeline. The predicate function should return true when the target element is found.

Example:

pipeline.BinarySearch(func(item int) bool { return item == targetValue })

func (*Pipeline[T]) Distinct

func (p *Pipeline[T]) Distinct(equal func(a, b T) bool) *Pipeline[T]

Distinct adds a distinct operation to the pipeline. The equal function should return true when two items are considered equal.

Example:

pipeline.Distinct(func(a, b User) bool {
    return a.ID == b.ID && a.Role == b.Role
})

func (*Pipeline[T]) Execute

func (p *Pipeline[T]) Execute() ([]T, error)

Execute runs all operations in the pipeline in sequence. Returns the final result or an error if any operation fails.

func (*Pipeline[T]) Filter

func (p *Pipeline[T]) Filter(predicate func(T) bool) *Pipeline[T]

Filter adds a filter operation to the pipeline. The predicate function should return true for items to keep in the result.

Example:

pipeline.Filter(func(item Product) bool {
    return item.Price > 1000 && item.InStock
})

func (*Pipeline[T]) Find

func (p *Pipeline[T]) Find(predicate func(T) bool) *Pipeline[T]

Find adds a find operation to the pipeline. The predicate function should return true for items to be included in the result.

Example:

pipeline.Find(func(order Order) bool {
    return order.Status == "Pending" && order.Total > 100
})

func (*Pipeline[T]) GetOperations

func (p *Pipeline[T]) GetOperations() []Operation[T]

GetOperations returns the slice of operations in the pipeline.

func (*Pipeline[T]) HeapSort

func (p *Pipeline[T]) HeapSort(comparator func(a, b T) bool) *Pipeline[T]

HeapSort adds a heap sort operation to the pipeline. The comparator function should return true when a should come before b in the sorted result.

Example:

pipeline.HeapSort(func(a, b User) bool {
    return a.Score > b.Score // Sort by score in descending order
})

func (*Pipeline[T]) LinearSearch

func (p *Pipeline[T]) LinearSearch(predicate func(T) bool) *Pipeline[T]

LinearSearch adds a linear search operation to the pipeline. The predicate function should return true when the target element is found.

Example:

pipeline.LinearSearch(func(user User) bool {
    return user.Email == "example@email.com"
})

func (*Pipeline[T]) LinearSearchExact

func (p *Pipeline[T]) LinearSearchExact(target T) *Pipeline[T]

LinearSearchExact adds a linear search operation that looks for an exact match.

Example:

pipeline.LinearSearchExact(targetUser)

func (*Pipeline[T]) Map

func (p *Pipeline[T]) Map(mapper func(T) T) *Pipeline[T]

Map adds a map operation to the pipeline. The mapper function defines how each element should be transformed.

Example:

pipeline.Map(func(user User) User {
    user.Name = strings.ToUpper(user.Name)
    return user
})

func (*Pipeline[T]) MergeSort

func (p *Pipeline[T]) MergeSort(comparator func(a, b T) bool) *Pipeline[T]

MergeSort adds a merge sort operation to the pipeline. The comparator function should return true when a should come before b in the sorted result.

Example:

pipeline.MergeSort(func(a, b Order) bool {
    return a.Priority > b.Priority // Sort by priority in descending order
})

func (*Pipeline[T]) QuickSort

func (p *Pipeline[T]) QuickSort(comparator func(a, b T) bool) *Pipeline[T]

QuickSort adds a quicksort operation to the pipeline. The comparator function should return true when a should come before b in the sorted result.

Example:

pipeline.QuickSort(func(a, b Product) bool {
    return a.Price < b.Price // Sort by price in ascending order
})

func (*Pipeline[T]) Reduce

func (p *Pipeline[T]) Reduce(reducer func(acc, item T) T) *Pipeline[T]

Reduce adds a reduce operation to the pipeline. The reducer function combines the accumulator with each item to produce a new accumulator.

Example:

pipeline.Reduce(func(acc, item Order) Order {
    acc.TotalAmount += item.Amount
    return acc
})

func (*Pipeline[T]) Skip

func (p *Pipeline[T]) Skip(count int) *Pipeline[T]

Skip adds a skip operation to the pipeline. The count parameter specifies how many elements to skip from the start.

Example:

pipeline.Skip(5) // Skip first 5 elements

func (*Pipeline[T]) Take

func (p *Pipeline[T]) Take(count int) *Pipeline[T]

Take adds a take operation to the pipeline. The count parameter specifies how many elements to select from the start.

Example:

pipeline.Take(5) // Select first 5 elements

func (*Pipeline[T]) WithData

func (p *Pipeline[T]) WithData(data []T) *Pipeline[T]

WithData sets the initial data for the Pipeline. It can be used with NewPipeline to set data after pipeline creation.

Example:

pipeline := NewPipeline[int]().
	WithData([]int{1, 2, 3, 4, 5}).
	Filter(func(x int) bool { return x > 2 }).
	Map(func(x int) int { return x * 2 }).
	QuickSort(func(a, b int) bool { return a < b })

result, err := pipeline.Execute()

type QuickSortOperation

type QuickSortOperation[T any] struct {
	Comparator func(a, b T) bool
}

QuickSortOperation sorts data using the quicksort algorithm. It provides efficient in-place sorting with O(n log n) average time complexity.

func (*QuickSortOperation[T]) Apply

func (q *QuickSortOperation[T]) Apply(data []T) ([]T, error)

Apply performs the quicksort operation on the data. It sorts the data in-place based on the provided comparator function.

Example:

pipeline := NewPipeline[int]().
    QuickSort(func(a, b int) bool { return a < b })
result, err := pipeline.Execute()

type ReduceOperation

type ReduceOperation[T any] struct {
	Reducer func(acc, item T) T
}

ReduceOperation aggregates all elements in the data into a single value. It applies the reducer function sequentially from left to right.

func (*ReduceOperation[T]) Apply

func (r *ReduceOperation[T]) Apply(data []T) ([]T, error)

Apply performs the reduce operation on the data. It returns a slice containing the single accumulated result. Returns an error if the input slice is empty.

Example:

pipeline := NewPipeline[int]().
    Reduce(func(acc, item int) int { return acc + item })
result, err := pipeline.Execute() // Sums all numbers

type SkipOperation

type SkipOperation[T any] struct {
	Count int
}

SkipOperation bypasses a specified number of elements from the beginning of the data. It returns the remaining elements while preserving their order.

func (*SkipOperation[T]) Apply

func (s *SkipOperation[T]) Apply(data []T) ([]T, error)

Apply performs the skip operation on the data. It returns a new slice excluding the first Count elements.

Example:

pipeline := NewPipeline[string]().
    Skip(2) // Skip first 2 elements
result, err := pipeline.Execute()

type TakeOperation

type TakeOperation[T any] struct {
	Count int
}

TakeOperation selects a specified number of elements from the beginning of the data. It preserves the order of the selected elements.

func (*TakeOperation[T]) Apply

func (t *TakeOperation[T]) Apply(data []T) ([]T, error)

Apply performs the take operation on the data. It returns a new slice containing the first Count elements.

Example:

pipeline := NewPipeline[int]().
    Take(3) // Take first 3 elements
result, err := pipeline.Execute()

type User

type User struct {
	ID     int
	Name   string
	Active bool
}

User is another common type used for testing.

Jump to

Keyboard shortcuts

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