arr

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 7, 2025 License: MIT Imports: 5 Imported by: 2

README

Array Package

tests

The arr package provides a comprehensive set of utilities for working with arrays, slices, and maps in Go. It offers a collection of functions to simplify common array operations and manipulations.

Features

  • Array Manipulation

    • Filter arrays based on conditions
    • Map arrays to new values
    • Reverse array order
    • Shuffle array elements
    • Split arrays into chunks
    • Merge multiple arrays
    • Remove elements by index
    • Move elements up/down by index
  • Array Analysis

    • Find minimum and maximum values
    • Calculate sum of numeric arrays
    • Count elements
    • Count elements by condition
    • Check if array contains specific values
    • Check if array contains all values
    • Find index of elements
    • Get unique values
  • Map Operations

    • Extract keys from maps
    • Extract values from maps
    • Group array elements by key
    • Check map equality
  • Iteration

    • Iterate over array elements
    • Filter empty values

Installation

go get github.com/dracory/arr

Usage Examples

Filtering Arrays
package main

import (
    "fmt"
    "github.com/dracory/arr"
)

func main() {
    numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    
    // Filter even numbers
    evenNumbers := arr.Filter(numbers, func(n int) bool {
        return n%2 == 0
    })
    
    fmt.Println(evenNumbers) // [2 4 6 8 10]
}
Mapping Arrays
package main

import (
    "fmt"
    "github.com/dracory/arr"
)

func main() {
    numbers := []int{1, 2, 3, 4, 5}
    
    // Double each number
    doubled := arr.Map(numbers, func(n int) int {
        return n * 2
    })
    
    fmt.Println(doubled) // [2 4 6 8 10]
}
Array Manipulation
package main

import (
    "fmt"
    "github.com/dracory/arr"
)

func main() {
    numbers := []int{1, 2, 3, 4, 5}
    
    // Reverse the array
    reversed := arr.Reverse(numbers)
    fmt.Println(reversed) // [5 4 3 2 1]
    
    // Shuffle the array
    shuffled := arr.Shuffle(numbers)
    fmt.Println(shuffled) // Random order
    
    // Split into chunks
    chunks := arr.Split(numbers, 2)
    fmt.Println(chunks) // [[1 2] [3 4] [5]]
}
Map Operations
package main

import (
    "fmt"
    "github.com/dracory/arr"
)

func main() {
    userMap := map[string]string{
        "name": "John",
        "age": "30",
        "email": "[email protected]",
    }
    
    // Get all keys
    keys := arr.Keys(userMap)
    fmt.Println(keys) // ["name" "age" "email"]
    
    // Get all values
    values := arr.Values(userMap)
    fmt.Println(values) // ["John" "30" "[email protected]"]
}
Array Analysis
package main

import (
    "fmt"
    "github.com/dracory/arr"
)

func main() {
    numbers := []int{5, 2, 9, 1, 7, 3, 8, 4, 6}
    
    // Find minimum
    min := arr.Min(numbers)
    fmt.Println(min) // 1
    
    // Find maximum
    max := arr.Max(numbers)
    fmt.Println(max) // 9
    
    // Calculate sum
    sum := arr.Sum(numbers)
    fmt.Println(sum) // 45
    
    // Count elements
    count := arr.Count(numbers)
    fmt.Println(count) // 9
    
    // Get unique values
    duplicates := []int{1, 2, 2, 3, 3, 3, 4, 4, 4, 4}
    unique := arr.Unique(duplicates)
    fmt.Println(unique) // [1 2 3 4]
}

Error Handling

Most functions in the arr package handle errors gracefully:

  • Empty arrays return appropriate zero values
  • Index out of bounds errors are prevented
  • Type mismatches are handled safely

Performance Considerations

  • The package is designed for convenience rather than maximum performance
  • For large arrays, consider using standard Go operations for better performance
  • Some operations like Shuffle and Reverse modify arrays in-place when possible

License

This package is part of the dracory/base project and is licensed under the same terms. See the main README.md for license information.

Documentation

Overview

Package arr contains functions to interact with arrays, slices, and sometimes maps.

The package is imported like this:

import "github.com/gouniverse/base/arr"

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Contains

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

func ContainsAll

func ContainsAll[T comparable](a, b []T) bool

ContainsAll checks if slice 'a' contains all elements of slice 'b', regardless of order.

func Count

func Count[T comparable](collection []T) (count int)

Count counts the number of elements in the collection.

func CountBy

func CountBy[T any](collection []T, predicate func(item T) bool) (count int)

CountBy counts the number of elements in the collection for which predicate is true.

func Each

func Each[T any](collection []T, iteratee func(item T, index int))

Each iterates over elements of collection and invokes iteratee for each element.

func Equals

func Equals[T comparable](a, b []T) bool

Equals checks if two slices are equal.

This function assumes that the slices contain comparable types.

It first checks if the slices have the same length. If not, it immediately returns false.

If the slices have the same length, it then checks if the elements are equal. If it finds an element that is not equal, it immediately returns false.

If it checks all elements and finds no unequal elements, it returns true.

func Filter

func Filter[V any](collection []V, predicate func(item V, index int) bool) []V

Filter iterates over elements of collection, returning an array of all elements predicate returns truthy for.

func FilterEmpty

func FilterEmpty(slice []string) []string

FilterEmpty takes a slice of strings and returns a new slice with all empty strings removed.

Example:

arr.FilterEmpty([]string{"", "hello", "", "world"}) // returns []string{"hello", "world"}

Parameters: - slice: the slice of strings to filter.

Returns: - []string: a new slice with all empty strings removed.

func GroupBy

func GroupBy[T any, U comparable](collection []T, iteratee func(item T) U) map[U][]T

GroupBy returns an object composed of keys generated from the results of running each element of collection through iteratee.

func Index

func Index[T comparable](slice []T, item T) int

Index finds the index of the first occurrence of an item in a slice.

Returns -1 if the item is not found.

func IndexMoveDown

func IndexMoveDown[T any](slice []T, index int) []T

indexMoveDown moves the element at the given index down

Business logic: - if the index is last index, will be ignored - if the index out of bounds, will be ignored

Parameters: - slice: the slice to move the element from - index: the index of the element to move

Returns: - []T: the new slice

Example:

arr := []int{1, 2, 3, 4}
result := IndexMoveDown(arr, 1)
// result is now [1, 4, 2, 3]

func IndexMoveUp

func IndexMoveUp[T any](slice []T, index int) []T

indexMoveUp moves the element at the given index up

Business logic: - if the index is first index, will be ignored - if the index out of bounds, will be ignored

Parameters: - slice: the slice to move the element from - index: the index of the element to move

Returns: - []T: the new slice

Example:

indices := []int{1, 2, 3, 4, 5}
IndexMoveUp(indices, 2)
fmt.Println(indices) // [1, 3, 2, 4, 5]

func IndexRemove

func IndexRemove[T any](slice []T, index int) []T

IndexRemove removes the element at the given index from the slice.

Parameters: - slice: the slice to remove the element from. - index: the index of the element to remove.

Returns: - []T: a new slice with the element at the given index removed.

Business Logic: - If the index is out of bounds, the original slice is returned unchanged. - This function does not panic on an out-of-bounds index.

Example:

arr := []int{1, 2, 3, 4}
result := IndexRemove(arr, 2)
// result is now [1, 2, 4]

func Keys

func Keys[K comparable, V any](in map[K]V) []K

Keys creates an array of the map keys.

func Map

func Map[T any, R any](collection []T, iteratee func(item T, index int) R) []R

Map manipulates a slice and transforms it to a slice of another type.

func Max

func Max[T constraints.Ordered](collection []T) T

Max searches the maximum value of a collection.

func Merge

func Merge[T any](slices ...[]T) []T

Merge merges multiple slices into a single slice.

func Min

func Min[T constraints.Ordered](collection []T) T

Min search the minimum value of a collection.

func Random

func Random[T any](slice []T) T

Random returns a random element from the provided slice. It uses Go generics, so it works with slices of any comparable type T. If the slice is empty, it returns the zero value of type T and false.

func Reverse

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

Reverse reverses array so that the first element becomes the last, the second element becomes the second to last, and so on.

func Shuffle

func Shuffle[T any](collection []T) []T

Shuffle returns an array of shuffled values. Uses the Fisher-Yates shuffle algorithm.

func Split

func Split[T any](collection []T, size int) [][]T

Split returns an array of elements split into groups the length of size. If array can't be split evenly,

func Sum

func Sum[T constraints.Float | constraints.Integer | constraints.Complex](collection []T) T

Sum sums the values in a collection. If collection is empty 0 is returned.

func Unique

func Unique[T comparable](collection []T) []T

Unique returns a duplicate-free version of an array, in which only the first occurrence of each element is kept.

func Values

func Values[K comparable, V any](in map[K]V) []V

Values creates an array of the map values.

Types

This section is empty.

Jump to

Keyboard shortcuts

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