sliceutil

package
v1.130.4 Latest Latest
Warning

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

Go to latest
Published: Mar 31, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package sliceutil provides generic, allocation-conscious helpers for common slice operations and numeric dataset summarization.

Problem

Go intentionally keeps slice operations minimal in the standard library. Teams typically re-implement the same small helpers for filter/map/reduce in multiple packages, and statistical summary code is often copied with subtle differences. This package centralizes those patterns into a reusable, type-safe API.

What It Provides

Functional slice primitives:

  • Filter: returns a new slice containing elements that satisfy a predicate.
  • Map: returns a new slice with each element transformed to a new type.
  • Reduce: folds a slice into a single value using an accumulator.

Descriptive statistics for numeric slices:

  • Stats: computes a DescStats summary for any numeric slice type.
  • DescStats includes count, sum, min/max (+ indexes), range, mode, mean/median, entropy, variance, standard deviation, skewness, and excess kurtosis.

Key Features

  • Generic APIs (`S ~[]E`) that work with native and named slice types.
  • Functional helpers include element index in callbacks for context-aware transforms.
  • Numeric statistics are available for all typeutil.Number types.
  • Safe error behavior for invalid input: Stats returns an error for empty slices.
  • Clear composition model: use Filter, Map, and Reduce in pipelines, then summarize results with Stats.

Usage

adults := sliceutil.Filter(users, func(_ int, u User) bool { return u.Age >= 18 })
names := sliceutil.Map(adults, func(_ int, u User) string { return u.Name })
total := sliceutil.Reduce([]int{1, 2, 3, 4}, 0, func(_ int, v int, acc int) int {
    return acc + v
})
_ = names
_ = total

ds, err := sliceutil.Stats([]int{53, 83, 13, 79})
if err != nil {
    return err
}
_ = ds.Mean

This package is ideal for Go services and libraries that want concise, predictable slice transformations and lightweight statistical summaries without pulling in heavy data-processing dependencies.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Filter

func Filter[S ~[]E, E any](s S, f func(int, E) bool) S

Filter returns a new slice containing only elements for which f returns true.

Example
package main

import (
	"fmt"

	"github.com/tecnickcom/gogen/pkg/sliceutil"
)

func main() {
	s := []string{"Hello", "World", "Extra"}

	filterFn := func(_ int, v string) bool { return v == "World" }

	s2 := sliceutil.Filter(s, filterFn)

	fmt.Println(s2)

}
Output:
[World]

func Map

func Map[S ~[]E, E any, U any](s S, f func(int, E) U) []U

Map returns a new slice containing f applied to each element of s.

Example
package main

import (
	"fmt"

	"github.com/tecnickcom/gogen/pkg/sliceutil"
)

func main() {
	s := []string{"Hello", "World", "Extra"}

	mapFn := func(k int, v string) int { return k + len(v) }

	s2 := sliceutil.Map(s, mapFn)

	fmt.Println(s2)

}
Output:
[5 6 7]

func Reduce

func Reduce[S ~[]E, E any, U any](s S, init U, f func(int, E, U) U) U

Reduce folds s into one value by repeatedly applying f to each element and accumulator state.

Example
package main

import (
	"fmt"

	"github.com/tecnickcom/gogen/pkg/sliceutil"
)

func main() {
	s := []int{2, 3, 5, 7, 11}

	init := 97
	reduceFn := func(k, v, r int) int { return k + v + r }

	r := sliceutil.Reduce(s, init, reduceFn)

	fmt.Println(r)

}
Output:
135

Types

type DescStats

type DescStats[V typeutil.Number] struct {
	// Count is the total number of items in the data set.
	Count int `json:"count"`

	// Entropy computes the Shannon entropy of a distribution.
	Entropy float64 `json:"entropy"`

	// ExKurtosis is the population excess kurtosis of the data set.
	// The kurtosis is defined by the 4th moment of the mean divided by the squared variance.
	// The excess kurtosis subtracts 3.0 so that the excess kurtosis of the normal distribution is zero.
	ExKurtosis float64 `json:"exkurtosis"`

	// Max is the maximum value of the data.
	Max V `json:"max"`

	// MaxID is the index (key) of the Max malue in a data set.
	MaxID int `json:"maxid"`

	// Mean or Average is a central tendency of the data.
	Mean float64 `json:"mean"`

	// MeanDev is the Mean Deviation or Mean Absolute Deviation.
	// It is an average of absolute differences between each value in the data, and the average of all values.
	MeanDev float64 `json:"meandev"`

	// Median is the value that divides the data into 2 equal parts.
	// When the data is sorted, the number of terms on the left and right side of median is the same.
	Median float64 `json:"median"`

	// Min is the minimal value of the data.
	Min V `json:"min"`

	// MinID is the index (key) of the Min malue in a data set.
	MinID int `json:"minid"`

	// Mode is the term appearing maximum time in data set.
	// It is the term that has the highest frequency.
	Mode V `json:"mode"`

	// ModeFreq is the frequency of the Mode value.
	ModeFreq int `json:"modefreq"`

	// Range is the difference between the highest (Max) and lowest (Min) value.
	Range V `json:"range"`

	// Skewness is a measure of the asymmetry of the probability distribution of a real-valued random variable about its mean.
	// Provides the adjusted Fisher-Pearson standardized moment coefficient.
	Skewness float64 `json:"skewness"`

	// StdDev is the Standard deviation of the data.
	// It measures the average distance between each quantity and mean.
	StdDev float64 `json:"stddev"`

	// Sum of all the values in the data.
	Sum V `json:"sum"`

	// Variance is a square of average distance between each quantity and Mean.
	Variance float64 `json:"variance"`
}

DescStats contains descriptive statistics items for a data set.

func Stats

func Stats[S ~[]V, V typeutil.Number](s S) (*DescStats[V], error)

Stats computes a DescStats summary for a numeric slice including count, sum, min/max, range, mode, mean, median, and shape metrics. Returns error if the slice is empty.

Example
package main

import (
	"fmt"
	"log"

	"github.com/tecnickcom/gogen/pkg/sliceutil"
)

func main() {
	data := []int{53, 83, 13, 79, 13, 37, 83, 29, 37, 13, 83, 83}

	ds, err := sliceutil.Stats(data)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Count:      %d\n", ds.Count)
	fmt.Printf("Entropy:    %.3f\n", ds.Entropy)
	fmt.Printf("ExKurtosis: %.3f\n", ds.ExKurtosis)
	fmt.Printf("Max:        %d\n", ds.Max)
	fmt.Printf("MaxID:      %d\n", ds.MaxID)
	fmt.Printf("Mean:       %.3f\n", ds.Mean)
	fmt.Printf("MeanDev:    %.3f\n", ds.MeanDev)
	fmt.Printf("Median:     %.3f\n", ds.Median)
	fmt.Printf("Min:        %d\n", ds.Min)
	fmt.Printf("MinID:      %d\n", ds.MinID)
	fmt.Printf("Mode:       %d\n", ds.Mode)
	fmt.Printf("ModeFreq:   %d\n", ds.ModeFreq)
	fmt.Printf("Range:      %d\n", ds.Range)
	fmt.Printf("Skewness:   %.3f\n", ds.Skewness)
	fmt.Printf("StdDev:     %.3f\n", ds.StdDev)
	fmt.Printf("Sum:        %d\n", ds.Sum)
	fmt.Printf("Variance:   %.3f\n", ds.Variance)

}
Output:
Count:      12
Entropy:    2.302
ExKurtosis: -1.910
Max:        83
MaxID:      1
Mean:       50.500
MeanDev:    0.000
Median:     45.000
Min:        13
MinID:      2
Mode:       83
ModeFreq:   4
Range:      70
Skewness:   -0.049
StdDev:     30.285
Sum:        606
Variance:   917.182

Jump to

Keyboard shortcuts

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