merge

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jun 25, 2025 License: Apache-2.0 Imports: 2 Imported by: 1

README

merge

GoDoc Build Status Coverage Status Go Report Card Apache 2 License

merge is a Go package for quickly combining slices of objects together into. This package supports updating objects with the same key and returns sorted results.

Install

go get github.com/adamdecaf/merge

Example

Given a few example games where players score goals we can combine those to find their total scores.

type Player struct {
	Name  string
	Goals int
}

game1 := []Player{
	{Name: "John Doe", Goals: 2},
	{Name: "Jane Doe", Goals: 1},
}
game2 := []Player{
	{Name: "Jane Doe", Goals: 2},
}
game3 := []Player{
	{Name: "Other Guy", Goals: 1},
}
game4 := []Player{
	{Name: "Jane Doe", Goals: 1},
	{Name: "Other Girl", Goals: 5},
}

out := Slices(
	func(p Player) string {
		return p.Name
	},
	func(p1 *Player, p2 *Player) {
		p1.Goals += p2.Goals
	},
	game1, game2, game3, game4,
)


expected := []Player{
	{Name: "John Doe", Goals: 2},
	{Name: "Jane Doe", Goals: 4},
	{Name: "Other Guy", Goals: 1},
	{Name: "Other Girl", Goals: 5},
}

Supported and tested platforms

  • 64-bit Linux (Ubuntu, Debian), macOS, and Windows

License

Apache License 2.0 - See LICENSE for details.

Documentation

Overview

Package merge provides functionality to merge multiple slices into a single sorted slice, combining values with the same key using a user-defined combiner function.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Slices

func Slices[K constraints.Ordered, V any](key func(V) K, combiner func(*V, *V), slices ...[]V) []V

Slices merges multiple slices into a single sorted slice based on a key function. It uses a treemap to maintain sorted order and combines values with the same key using the provided combiner function. If no combiner is provided (nil), the first value encountered for a given key is kept, and subsequent values are ignored.

The function is generic, allowing keys of any ordered type (K) and values of any type (V). The key function extracts a key from each value, and the combiner function (if provided) modifies the stored value based on a new value with the same key.

Parameters:

  • key: A function that extracts a comparable key of type K from a value of type V.
  • combiner: A function that combines two values of type V, modifying the first value based on the second. If nil, the first value for a key is retained.
  • slices: Variable number of input slices of type V to merge.

Returns:

A sorted slice containing the merged values, ordered by their keys.

Types

This section is empty.

Jump to

Keyboard shortcuts

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