set

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2023 License: MIT Imports: 8 Imported by: 0

README

Go Report Card License License Stay with Ukraine

Set

Set is a Go package that provides a parameterized Set data structure.

A Set can contain any type of object, including simple and complex types. It provides basic set operations, such as Add, Delete, Contains, and Len. In addition, it also provides complex set operations, such as Union, Intersection, Difference, SymmetricDifference, IsSubset, and IsSuperset.

Installation

You can download and install the package by running:

go get github.com/goloop/set

Usage

Here's a simple example of how to use the Set package.

Basic functions
package main

import (
	"fmt"

	"github.com/goloop/set"
)

// Address is user's address.
type Address struct {
	City string
}

// User is the user type.
type User struct {
	Name    string   // a simple field of string type
	Age     int      // a simple field of int type
	Address *Address // nested fields
}

func main() {
	// Define a new sets.
	// Empty set, the type of set must be specified.
	iSet := set.New[int]()

	// A type can be defined from the elements of a set.
	sSet := set.New("one", "two", "three")

	// Support for complex types such as slice, arrays, maps, structures.
	cSet := set.New[User](
		User{
			Name: "John",
			Age:  21,
			Address: &Address{
				City: "Kyiv",
			},
		},
		User{
			Name: "Bob",
			Age:  22,
			Address: &Address{
				City: "Chernihiv",
			},
		},
	)

	// Add elements to the set.
	iSet.Add(1, 2, 3, 4)
	sSet.Add("three", "four", "five")
	cSet.Add(
		User{
			Name: "John",
			Age:  21,
			Address: &Address{
				City: "Kyiv",
			},
		}, // duplicate
		User{
			Name: "Victoria",
			Age:  23,
			Address: &Address{
				City: "Chernihiv",
			},
		},
	)

	// Check the size of the set.
	fmt.Println("\nLength:")
	fmt.Println("iSet: ", iSet.Len())
	fmt.Println("sSet: ", sSet.Len())
	fmt.Println("cSet: ", cSet.Len())

	// Elements.
	fmt.Println("\nElements:")
	fmt.Println("iSet: ", iSet.Elements())
	fmt.Println("sSet: ", sSet.Elements())
	fmt.Println("cSet: ", cSet.Elements())

	// Check if the set contains a certain element.
	fmt.Println("\nContains:")
	fmt.Println("iSet: ", iSet.Contains(3), iSet.Contains(10))
	fmt.Println("sSet: ", sSet.Contains("five"), sSet.Contains("nine"))
	fmt.Println("cSet: ",
		cSet.Contains(
			User{
				Name: "John",
				Age:  21,
				Address: &Address{
					City: "Kyiv",
				},
			}, // [!] new object here
		),
		cSet.Contains(
			User{
				Name: "Adam",
				Age:  23,
				Address: &Address{
					City: "Chernihiv",
				},
			},
		),
	)

	// Delete.
	iSet.Delete(1, 2, 4)
	sSet.Delete("four")
	cSet.Delete(
		User{
			Name: "John",
			Age:  21,
			Address: &Address{
				City: "Kyiv",
			},
		},
	)

	fmt.Println("\nElements after deletion:")
	fmt.Println("iSet: ", iSet.Elements())
	fmt.Println("sSet: ", sSet.Elements())
	fmt.Println("cSet: ", cSet.Elements())
}


// Output:
// Length:
// iSet:  4
// sSet:  5
// cSet:  3

// Elements:
// iSet:  [1 2 3 4]
// sSet:  [two three four five one]
// cSet:  [{John 21 0xc033} {Bob 22 0xc055} {Victoria 23 0xc077}]

// Contains:
// iSet:  true false
// sSet:  true false
// cSet:  true false

// Elements after deletion:
// iSet:  [3]
// sSet:  [one two three five]
// cSet:  [{Bob 22 0xc055} {Victoria 23 0xc077}]

See example here.

Operations on set
package main

import (
	"fmt"

	"github.com/goloop/set"
)

func main() {
	a := set.New(1, 3, 5, 7)
	b := set.New(0, 2, 4, 7)

	// Union.
	c := a.Union(b)
	fmt.Println("Union:")
	fmt.Println("a: ", a.Elements())
	fmt.Println("b: ", b.Elements())
	fmt.Println("c: ", c.Elements())

	// Intersection.
	c = a.Intersection(b)
	fmt.Println("\nIntersection:")
	fmt.Println("a: ", a.Elements())
	fmt.Println("b: ", b.Elements())
	fmt.Println("c: ", c.Elements())

	// Difference.
	c = a.Difference(b)
	fmt.Println("\nDifference:")
	fmt.Println("a: ", a.Elements())
	fmt.Println("b: ", b.Elements())
	fmt.Println("c: ", c.Elements())

	// SymmetricDifference.
	c = a.SymmetricDifference(b)
	fmt.Println("\nSymmetricDifference:")
	fmt.Println("a: ", a.Elements())
	fmt.Println("b: ", b.Elements())
	fmt.Println("c: ", c.Elements())

	// IsSubset.
	a = set.New(1, 2, 3)
	b = set.New(1, 2, 3, 4, 5, 6)
	fmt.Println("\nSubset:")
	fmt.Println("a: ", a.Elements())
	fmt.Println("b: ", b.Elements())
	fmt.Println("result: ", a.IsSubset(b))

	// IsSuperset.
	a = set.New(1, 2, 3)
	b = set.New(1, 2, 3, 4, 5, 6)
	fmt.Println("\nIsSuperset:")
	fmt.Println("a: ", a.Elements())
	fmt.Println("b: ", b.Elements())
	fmt.Println("result: ", a.IsSuperset(b))

}

// Output:
// Union:
// a:  [3 5 7 1]
// b:  [0 2 4 7]
// c:  [7 2 4 0 1 3 5]

// Intersection:
// a:  [1 3 5 7]
// b:  [7 0 2 4]
// c:  [7]

// Difference:
// a:  [7 1 3 5]
// b:  [0 2 4 7]
// c:  [1 3 5]

// SymmetricDifference:
// a:  [1 3 5 7]
// b:  [0 2 4 7]
// c:  [4 3 5 1 0 2]

// Subset:
// a:  [3 1 2]
// b:  [1 2 3 4 5 6]
// result:  true

// IsSuperset:
// a:  [1 2 3]
// b:  [4 5 6 1 2 3]
// result:  false

See example here.

Other functions

Example 1.

package main

import (
	"fmt"

	"github.com/goloop/set"
)

// User object.
type User struct {
	Name string
	Age  int
}

func main() {
	// Simple set values.
	a := set.New(1, 3, 5, 7)
	b := set.New(0, 2, 4, 7)
	c := set.New(3, 4, 5, 6, 7, 8)

	// Update instance.
	a.Append(b, c) // a.Extend([]*set.Set[int]{b, c})
	fmt.Println("Append/Extend:", a.Elements())

	// Return sorted elements.
	fmt.Println("Sorted:", a.Sorted())
	fmt.Println("Reverse:", a.Sorted(func(a, b int) bool {
		return a > b
	}))

	// Clear.
	a.Clear()
	fmt.Println("Cleared:", a.Elements())

	// Complex set values.
	d := set.New(
		User{"John", 21},
		User{"Bob", 27},
		User{"Maya", 25},
	)

	fmt.Println("Sorted by Age:", d.Sorted(func(a, b User) bool {
		return a.Age < b.Age
	}))
	fmt.Println("Sorted by Name:", d.Sorted(func(a, b User) bool {
		return a.Name < b.Name
	}))
}

// Output:
// Append/Extend: [7 4 8 6 1 3 5 2 0]
// Sorted: [0 1 2 3 4 5 6 7 8]
// Reverse: [8 7 6 5 4 3 2 1 0]
// Cleared: []
// Sorted by Age: [{John 21} {Maya 25} {Bob 27}]
// Sorted by Name: [{Bob 27} {John 21} {Maya 25}]

See example here.

Example 2.

package main

import (
	"fmt"

	"github.com/goloop/set"
)

// User object.
type User struct {
	Name   string
	Age    int
	Gender string
}

func main() {
	s := set.New(
		User{"Alice", 20, "f"},
		User{"Bob", 30, "m"},
		User{"Charlie", 40, "m"},
		User{"Dave", 50, "m"},
		User{"Eve", 16, "f"},
	)

	// Filtered.
	fmt.Println("\nFiltered:")
	fmt.Println("Women:", s.Filtered(func(item User) bool {
		return item.Gender == "f"
	}))
	fmt.Println("Adults:", s.Filtered(func(item User) bool {
		return item.Age > 18
	}))

	// Filter.
	f := s.Filter(func(item User) bool {
		return item.Gender == "f" && item.Age > 18
	})
	fmt.Println("\nFilter:")
	fmt.Println("Adults women:", f.Elements())

	// Map.
	// Methods cannot support generics, so we need to use the set.Map
	// function to change the types of generated values.
	//
	// Better to use the Map method for simple types only, like:
	// int, uint, bool, etc.
	// s := set.New[int](1, 2, 3, 4)
	// m := s.Map(func(item int) int {
	//     return item * 2
	// }) // returns a new set with the values {2, 4, 6, 8}
	names := set.Map(s, func(item User) string {
		return item.Name
	})
	fmt.Println("\nMap:")
	fmt.Println("Names:", names.Elements())

	// Reduce.
	// Methods cannot support generics, so we need to use the set.Reduce
	// function to change the types of generated values.
	//
	// We can use the Reduce method for simple types only, like:
	// int, uint, bool, etc.
	// s := set.New[int](1, 2, 3, 4)
	// sum := s.Reduce(func(acc int, item int) int {
	//     return acc + item
	// }) // returns 10
	sum := set.Reduce(s, func(acc int, item User) int {
		return acc + item.Age
	})
	fmt.Println("\nReduce:")
	fmt.Println("Total age:", sum)

	// Any.
	fmt.Println("\nAny:")
	fmt.Println("Any adult:", s.Any(func(item User) bool {
		return item.Age > 18
	}))

	// All.
	fmt.Println("\nAll:")
	fmt.Println("All adults:", s.All(func(item User) bool {
		return item.Age > 18
	}))
}

// Output:
// Filtered:
// Women: [{Eve 16 f} {Alice 20 f}]
// Adults: [{Alice 20 f} {Bob 30 m} {Charlie 40 m} {Dave 50 m}]

// Filter:
// Adults women: [{Alice 20 f}]

// Map:
// Names: [Alice Bob Charlie Dave Eve]

// Reduce:
// Total age: 156

// Any:
// Any adult: true

// All:
// All adults: false

See example here.

Documentation

You can read more about the Set package and its functions on Godoc.

Documentation

Overview

Package set provides a parameterized Set data structure for Go.

A Set can contain any type of object, including both simple and complex types. However, it is important to note that a Set can only contain either simple or complex types, not both.

This package provides basic set operations, such as Add, Delete, Contains, and Len. In addition, it also provides complex set operations, such as Union, Intersection, Difference, SymmetricDifference, IsSubset, and IsSuperset.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Add added in v1.0.1

func Add[T any](s *Set[T], items ...T)

Add adds the provided items to the set.

Example usage:

s := set.New[int]()
set.Add(s, 1, 2, 3) // s is 1, 2, 3

func AddWithContext added in v1.0.1

func AddWithContext[T any](ctx context.Context, s *Set[T], items ...T) error

AddWithContext adds the provided items to the set.

The function takes a context as the first argument and can be interrupted externally.

func Contains added in v1.0.1

func Contains[T any](s *Set[T], item T) bool

Contains returns true if the set contains all of the provided items, otherwise it returns false.

Example usage:

s := set.New[int]()
set.Add(s, 1, 2, 3) // s is 1, 2, 3
set.Contains(s, 1)  // returns true
set.Contains(s, 4)  // returns false

func ContainsWithContext added in v1.0.1

func ContainsWithContext[T any](
	ctx context.Context,
	s *Set[T],
	item T,
) (bool, error)

ContainsWithContext returns true if the set contains all of the provided items, otherwise it returns false.

The function takes a context as the first argument and can be interrupted externally.

func Delete added in v1.0.1

func Delete[T any](s *Set[T], items ...T)

Delete deletes the provided items from the set.

Example usage:

s := set.New[int]()
set.Add(s, 1, 2, 3) // s is 1, 2, 3
set.Delete(s, 1, 2) // s is 3

func DeleteWithContext added in v1.0.1

func DeleteWithContext[T any](
	ctx context.Context,
	s *Set[T],
	items ...T,
) error

DeleteWithContext deletes the provided items from the set.

The function takes a context as the first argument and can be interrupted externally.

func Elements added in v1.0.0

func Elements[T any](s *Set[T]) []T

Elements returns a slice of the elements of the set.

func ElementsWithContext added in v1.0.0

func ElementsWithContext[T any](ctx context.Context, s *Set[T]) ([]T, error)

ElementsWithContext returns a slice of the elements of the set using the provided context.

The function takes a context as the first argument and can be interrupted externally.

func Filtered added in v1.0.1

func Filtered[T any](s *Set[T], fn func(item T) bool) []T

Filtered returns a slice of the elements of the set that satisfy the provided filter function.

func FilteredWithContext added in v1.0.1

func FilteredWithContext[T any](
	ctx context.Context,
	s *Set[T],
	fn func(item T) bool,
) ([]T, error)

FilteredWithContext returns a slice of the elements of the set that satisfy the provided filter function using the provided context.

The function takes a context as the first argument and can be interrupted externally.

func Len added in v1.0.1

func Len[T any](s *Set[T]) int

Len returns the number of items in the set.

func ParallelTasks added in v1.1.0

func ParallelTasks(v ...int) int

ParallelTasks returns the number of parallel tasks.

If the function is called without parameters, it returns the current value of parallelTasks.

A function can receive one or more values for parallelTasks, these values are added together to form the final result for parallelTasks. If the new value for parallelTasks is less than or equal to zero - it will be set to 1, if it is greater than maxParallelTasks - it will be set to maxParallelTasks.

func Reduce added in v0.7.0

func Reduce[T any, R any](s *Set[T], fn func(acc R, item T) R) R

Reduce returns a single value by applying the provided function to each item in the set and passing the result of previous function call as the first argument in the next call.

Example usage:

	type User struct {
			Name string
			Age  int
	}

 s := set.New[User]()
 s.Add(User{"John", 20}, User{"Jane", 30})

 sum := sort.Reduce(s, func(acc int, item User) int {
     return acc + item.Age
 }) // sum is 50

func ReduceWithContext added in v1.0.0

func ReduceWithContext[T any, R any](
	ctx context.Context,
	s *Set[T],
	fn func(acc R, item T) R,
) (R, error)

ReduceWithContext returns a single value by applying the provided function to each item in the set and passing the result of previous function call as the first argument in the next call.

The function is passed a context.Context as the first argument.

func Sorted added in v1.0.0

func Sorted[T any](s *Set[T], fns ...func(a, b T) bool) []T

Sorted returns a slice of the sorted elements of the set.

func SortedWithContext added in v1.0.0

func SortedWithContext[T any](ctx context.Context, s *Set[T],
	fns ...func(a, b T) bool) ([]T, error)

SortedWithContext returns a slice of the sorted elements of the set using the provided context.

The function takes a context as the first argument and can be interrupted externally.

Types

type Set

type Set[T any] struct {
	// contains filtered or unexported fields
}

Set is a set of any objects. The set can contain both simple and complex types. It is important to note that the set can only one specific type. This information is stored in the 'simple' field where -1 denotes complex objects, 0 denotes that the type hasn't been set yet, and 1 denotes simple objects. The actual elements are stored in a map called 'heap' where the keys are hashed string representations of the objects, and the values are the objects themselves.

func Copy added in v1.0.1

func Copy[T any](s *Set[T]) *Set[T]

Copy returns a new set with all the items from the set.

Example usage:

s1 := set.New[int](1, 2, 3)
s2 := set.Copy(s1)
fmt.Println(s2.Sorted()) // 1, 2, 3

func CopyWithContext added in v1.0.1

func CopyWithContext[T any](
	ctx context.Context,
	s *Set[T],
) (*Set[T], error)

CopyWithContext returns a new set with all the items from the set. The function is passed a context.Context as the first argument.

func Diff added in v0.7.3

func Diff[T any](s *Set[T], others ...*Set[T]) *Set[T]

Diff is an alias for Difference.

func DiffWithContext added in v1.0.0

func DiffWithContext[T any](
	ctx context.Context,
	s *Set[T],
	others ...*Set[T],
) (*Set[T], error)

DiffWithContext is an alias for DifferenceWithContext.

func Difference added in v0.7.3

func Difference[T any](s *Set[T], others ...*Set[T]) *Set[T]

Difference returns a new set with all the items that are in the set but not in the other set.

Example usage:

s1 := set.New[int](1, 2, 3)
s2 := set.New[int](3, 4, 5)
s3 := set.New[int](5, 6, 7)
s4 := set.New[int](7, 8, 9)

r := set.Difference(s1, s2, s3, s4)
fmt.Println(r.Sorted()) // 1, 2

func DifferenceWithContext added in v1.0.0

func DifferenceWithContext[T any](
	ctx context.Context,
	s *Set[T],
	others ...*Set[T],
) (*Set[T], error)

DifferenceWithContext returns a new set with all the items that are in the set but not in the other set.

func Filter added in v1.0.1

func Filter[T any](s *Set[T], fn func(item T) bool) *Set[T]

Filter returns a new set with all the items from the set that pass the test implemented by the provided function.

Example usage:

s := set.New[int](1, 2, 3, 4, 5)
r := set.Filter(s, func(item int) bool {
    return item%2 == 0
})
fmt.Println(r.Sorted()) // 2, 4

func FilterWithContext added in v1.0.1

func FilterWithContext[T any](
	ctx context.Context,
	s *Set[T],
	fn func(item T) bool,
) (*Set[T], error)

FilterWithContext returns a new set with all the items from the set that pass the test implemented by the provided function. The function is passed a context.Context as the first argument.

func Inter added in v1.0.0

func Inter[T any](s *Set[T], others ...*Set[T]) *Set[T]

Inter is a shortcut for Intersection.

func InterWithContext added in v1.0.0

func InterWithContext[T any](
	ctx context.Context,
	s *Set[T],
	others ...*Set[T],
) (*Set[T], error)

InterWithContext is a shortcut for IntersectionWithContext.

func Intersection added in v0.7.3

func Intersection[T any](s *Set[T], others ...*Set[T]) *Set[T]

Intersection returns a new set with all the items that are in both the set and in the other set.

Example usage:

s1 := set.New[int](1, 2, 3)
s2 := set.New[int](3, 4, 5)
s3 := set.New[int](5, 6, 7)
s4 := set.New[int](7, 8, 9)

r := set.Intersection(s1, s2, s3, s4)
fmt.Println(r.Sorted()) // 7

func IntersectionWithContext added in v1.0.0

func IntersectionWithContext[T any](
	ctx context.Context,
	s *Set[T],
	others ...*Set[T],
) (*Set[T], error)

IntersectionWithContext returns a new set with all the items that are in both the set and in the other set.

The function takes a context as the first argument and can be interrupted externally.

func Map added in v0.7.0

func Map[T any, R any](s *Set[T], fn func(item T) R) *Set[R]

Map returns a new set with the results of applying the provided function to each item in the set.

Example usage:

type User struct {
    Name string
    Age  int
}

s := set.New[User]()
s.Add(User{"John", 20}, User{"Jane", 30})

names := sort.Map(s, func(item User) string {
    return item.Name
})

fmt.Println(names.Elements()) // "Jane", "John"

func MapWithContext added in v1.0.0

func MapWithContext[T any, R any](
	ctx context.Context,
	s *Set[T],
	fn func(item T) R,
) (*Set[R], error)

MapWithContext returns a new set with the results of applying the provided function to each item in the set. The function is passed a context.Context as the first argument.

func New

func New[T any](items ...T) *Set[T]

New is a constructor function that creates a new Set[T] instance. It accepts an arbitrary number of items of a generic type 'T' which can be either simple types (e.g., int, string, bool) or complex types (e.g., struct, slice).

This function first creates a new, empty set. It then determines whether the Set is simple or complex based on the type of the first item, and caches this information for efficient subsequent operations. Finally, it adds the provided items to the Set.

Note: All items must be of the same type. If different types are provided, the behavior is undefined.

Example usage:

// Creating a set of simple type (int)
emptySet := set.New[int]()       // empty set of int
simpleSet := set.New(1, 2, 3, 4) // set of int

// Creating a set of complex type (struct).
type ComplexType struct {
    field1 int
    field2 string
}
complexSet := set.New(
    ComplexType{1, "one"},
    ComplexType{2, "two"},
)

// Adding an item to the set.
simpleSet.Add(5)
complexSet.Add(ComplexType{3, "three"})

// Checking if an item exists in the set.
existsSimple := simpleSet.Contains(3)                       // returns true
existsComplex := complexSet.Contains(ComplexType{2, "two"}) // returns true

// Getting the size of the set.
size := simpleSet.Len() // returns 5

func NewWithContext added in v1.0.0

func NewWithContext[T any](ctx context.Context, items ...T) *Set[T]

NewWithContext is a constructor function that creates a new Set[T] instance. It accepts a context.Context as the first argument, followed by an arbitrary number of items of a generic type 'T' which can be either simple types (e.g., int, string, bool) or complex types (e.g., struct, slice).

func Sdiff added in v0.7.3

func Sdiff[T any](s *Set[T], others ...*Set[T]) *Set[T]

Sdiff is an alias for SymmetricDifference.

func SdiffWithContext added in v1.0.0

func SdiffWithContext[T any](
	ctx context.Context,
	s *Set[T],
	others ...*Set[T],
) (*Set[T], error)

SdiffWithContext is an alias for SymmetricDifferenceWithContext.

func SymmetricDifference added in v0.7.3

func SymmetricDifference[T any](s *Set[T], others ...*Set[T]) *Set[T]

SymmetricDifference returns a new set with all the items that are in the set or in the other set but not in both.

Example usage:

s1 := set.New[int](1, 2, 3)
s2 := set.New[int](3, 4, 5)
s3 := set.New[int](5, 6, 7)
s4 := set.New[int](7, 8, 9)

r := set.SymmetricDifference(s1, s2, s3, s4)
fmt.Println(r.Sorted()) // 1, 2, 4, 6, 8, 9

func SymmetricDifferenceWithContext added in v1.0.0

func SymmetricDifferenceWithContext[T any](
	ctx context.Context,
	s *Set[T],
	others ...*Set[T],
) (*Set[T], error)

SymmetricDifferenceWithContext returns a new set with all the items that are in the set or in the other set but not in both.

func Union added in v0.7.3

func Union[T any](s *Set[T], others ...*Set[T]) *Set[T]

Union returns a new set with all the items that are in either the set or in the other set.

Example usage:

s1 := set.New[int](1, 2, 3)
s2 := set.New[int](3, 4, 5)
s3 := set.New[int](5, 6, 7)
s4 := set.New[int](7, 8, 9)

r := set.Union(s1, s2, s3, s4)
fmt.Println(r.Sorted()) // 1, 2, 3, 4, 5, 6, 7, 8, 9

func UnionWithContext added in v1.0.0

func UnionWithContext[T any](
	ctx context.Context,
	s *Set[T],
	others ...*Set[T],
) (*Set[T], error)

UnionWithContext returns a new set with all the items that are in either the set or in the other set.

The function takes a context as the first argument and can be interrupted externally.

func (*Set[T]) Add

func (s *Set[T]) Add(items ...T)

Add adds the given items to the set.

Example usage:

// Define a new set.
s := set.New[int]()

// Add elements to the set.
s.Add(1, 2, 3, 4) // s is 1, 2, 3, and 4

func (*Set[T]) All added in v0.6.0

func (s *Set[T]) All(fn func(item T) bool) bool

All returns true if all of the items in the set satisfy the provided predicate.

Example usage:

s := set.New[int]()
s.Add(1, 2, 3)

all := s.All(func(item int) bool {
	return item > 2
}) // all is false

func (*Set[T]) Any added in v0.6.0

func (s *Set[T]) Any(fn func(item T) bool) bool

Any returns true if any of the items in the set satisfy the provided predicate.

Example usage:

s := set.New[int]()
s.Add(1, 2, 3)

any := s.Any(func(item int) bool {
	return item > 2
}) // any is true

func (*Set[T]) Append added in v0.3.0

func (s *Set[T]) Append(sets ...*Set[T])

Append adds all elements from the provided sets to the current set.

Example usage:

s1 := set.New[int]()
s1.Add(1, 2, 3)

s2 := New[int]()
s2.Add(4, 5, 6)

s1.Append(s2)  // s1 now contains 1, 2, 3, 4, 5, 6

func (*Set[T]) Clear added in v0.5.0

func (s *Set[T]) Clear()

Clear removes all items from the set.

Example usage:

s := New[int]()
s.Add(1, 2, 3)

s.Clear() // s is now empty

func (*Set[T]) Contains

func (s *Set[T]) Contains(item T) bool

Contains returns true if the set contains the given item.

Example usage:

// Define a new set and add some elements.
s := set.New[int]()
s.Add(1, 2, 3, 4)

// Check if the set contains certain elements.
containsOne := s.Contains(1)  // returns true
containsFive := s.Contains(5) // returns false

func (*Set[T]) Copy added in v0.4.0

func (s *Set[T]) Copy() *Set[T]

Copy returns a new set with a copy of items in the set. This is useful when you want to copy the set.

Example usage:

s := set.New[int]()
s.Add(1, 2, 3)

copied := s.Copy() // copied contains 1, 2, 3

func (*Set[T]) Delete

func (s *Set[T]) Delete(items ...T)

Delete removes the given items from the set.

Example usage:

// Define a new set and add some elements
s := set.New[int]()
s.Add(1, 2, 3, 4)

// Remove elements from the set
s.Delete(1, 3) // s is 2 and 4

func (*Set[T]) Diff added in v0.2.0

func (s *Set[T]) Diff(set *Set[T]) *Set[T]

Diff is an alias for Difference.

func (*Set[T]) Difference

func (s *Set[T]) Difference(set *Set[T]) *Set[T]

Difference returns a new set with items in the first set but not in the second. This is useful when you want to find items that are unique to the first set.

Example usage:

s1 := set.New[int]()
s1.Add(1, 2, 3)

s2 := set.New[int]()
s2.Add(3, 4, 5)

difference := s1.Difference(s2)  // difference contains 1, 2

func (*Set[T]) Elements

func (s *Set[T]) Elements() []T

Elements returns all items in the set. This is useful when you need to iterate over the set, or when you need to convert the set to a slice ([]T). Note that the order of items is not guaranteed.

Example usage:

s := set.New[int]()
s.Add(1, 2, 3, 4)
elements := s.Elements()  // elements is []int{1, 2, 3, 4}

func (*Set[T]) Extend added in v0.3.0

func (s *Set[T]) Extend(sets []*Set[T])

Extend adds all elements from the provided slice of sets to the current set.

Example usage:

s1 := set.New[int]()
s1.Add(1, 2, 3)

s2 := set.New[int]()
s2.Add(4, 5, 6)

s1.Extend(s2)  // s1 now contains 1, 2, 3, 4, 5, 6

func (*Set[T]) Filter added in v0.6.0

func (s *Set[T]) Filter(fn func(item T) bool) *Set[T]

Filter returns a new set with items that satisfy the provided predicate.

Example usage:

s := set.New[int]()
s.Add(1, 2, 3, 4, 5)

filtered := s.Filter(func(item int) bool {
	return item > 3
}) // filtered contains 4, 5

func (*Set[T]) Filtered added in v0.6.0

func (s *Set[T]) Filtered(fn func(item T) bool) []T

Filtered returns slice of items that satisfy the provided predicate.

Example usage:

s := set.New[int]()
s.Add(1, 2, 3, 4, 5)

filtered := s.Filtered(func(item int) bool {
	return item > 3
}) // filtered contains 4, 5

func (*Set[T]) Inter added in v1.0.0

func (s *Set[T]) Inter(set *Set[T]) *Set[T]

Inter is an alias for Intersection.

func (*Set[T]) Intersection

func (s *Set[T]) Intersection(set *Set[T]) *Set[T]

Intersection returns a new set with items that exist only in both sets.

Example usage:

s1 := set.New[int]()
s1.Add(1, 2, 3)

s2 := set.New[int]()
s2.Add(3, 4, 5)

intersection := s1.Intersection(s2)  // intersection contains 3

func (*Set[T]) IsComplex added in v0.7.2

func (s *Set[T]) IsComplex() bool

IsComplex returns true if the objects in the set are complex, and false otherwise.

func (*Set[T]) IsSimple added in v0.7.2

func (s *Set[T]) IsSimple() bool

IsSimple determines the complexity of the objects in the set, i.e., whether the objects are simple or complex.

This method sets the field 'simple' based on the type of the object. If the set contains simple types such as byte, chan, bool, string, rune, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr, float32, float64, complex64, or complex128, the 'simple' field is set to 1.

If the set contains complex types such as struct, array, slice, map, func, etc., the 'simple' field is set to -1.

This method is invoked upon the creation of a set, and the complexity information is cached for efficient subsequent operations. It returns true if the objects in the set are simple, and false otherwise.

func (*Set[T]) IsSub added in v1.0.0

func (s *Set[T]) IsSub(set *Set[T]) bool

IsSub is an alias for IsSubset.

func (*Set[T]) IsSubset

func (s *Set[T]) IsSubset(set *Set[T]) bool

IsSubset returns true if all items in the first set exist in the second. This is useful when you want to check if all items of one set belong to another set.

Example usage:

s1 := set.New[int]()
s1.Add(1, 2, 3)

s2 := set.New[int]()
s2.Add(1, 2, 3, 4, 5)

isSubset := s1.IsSubset(s2)  // isSubset is true

func (*Set[T]) IsSup added in v1.0.1

func (s *Set[T]) IsSup(set *Set[T]) bool

IsSup is an alias for IsSuperset.

func (*Set[T]) IsSuperset

func (s *Set[T]) IsSuperset(set *Set[T]) bool

IsSuperset returns true if all items in the second set exist in the first. This is useful when you want to check if one set contains all items of another set.

Example usage:

s1 := set.New[int]()
s1.Add(1, 2, 3, 4, 5)

s2 := set.New[int]()
s2.Add(1, 2, 3)

isSuperset := s1.IsSuperset(s2)  // isSuperset is true

func (*Set[T]) Len

func (s *Set[T]) Len() int

Len returns the number of items in the set. This is useful when you need to know how many items are in the set.

Example usage:

s := set.New[int]()
s.Add(1, 2, 3, 4)
length := s.Len()  // length is 4

func (*Set[T]) Map added in v0.6.0

func (s *Set[T]) Map(fn func(item T) T) *Set[T]

Map returns a new set with the results of applying the provided function to each item in the set.

The result can only be of the same type as the elements of the set. For more flexibility, pay attention to the set.Reduce function.

Example usage:

s := set.New[int]()
s.Add(1, 2, 3)

mapped := s.Map(func(item int) int {
	return item * 2
}) // mapped contains 2, 4, 6

Due to the fact that methods in Go don't support generics to change the result type we have to use the set.Map function.

func (*Set[T]) Overwrite added in v0.5.0

func (s *Set[T]) Overwrite(items ...T)

Overwrite removes all items from the set and adds the provided items.

Example usage:

s := set.New[int]()
s.Add(1, 2, 3)
s.Elements() // returns []int{1, 2, 3}

s.Overwrite(5, 6, 7) // as s.Clear() and s.Add(5, 6, 7)
s.Elements() // returns []int{5, 6, 7}

func (*Set[T]) Reduce added in v0.6.0

func (s *Set[T]) Reduce(fn func(acc, item T) T) T

Reduce returns a single value by applying the provided function to each item in the set and passing the result of previous function call as the first argument in the next call.

The result can only be of the same type as the elements of the set. For more flexibility, pay attention to the set.Reduce function.

Example usage:

s := set.New[int]()
s.Add(1, 2, 3)

sum := s.Reduce(func(acc, item int) int) T {
	return acc + item
}) // sum is 6

func (*Set[T]) Sdiff added in v0.2.0

func (s *Set[T]) Sdiff(set *Set[T]) *Set[T]

Sdiff is an alias for SymmetricDifference.

func (*Set[T]) Sorted added in v0.2.0

func (s *Set[T]) Sorted(fns ...func(a, b T) bool) []T

Sorted returns a slice of the sorted elements of the set.

Example usage:

s := set.New[int]()
s.Add(3, 1, 2)

sorted := s.Sorted() // sorted contains 1, 2, 3

func (*Set[T]) SymmetricDifference

func (s *Set[T]) SymmetricDifference(set *Set[T]) *Set[T]

SymmetricDifference returns a new set with items in either the first or second set but not both. This is useful when you want to find items that are unique to each set.

Example usage:

s1 := set.New[int]()
s1.Add(1, 2, 3)

s2 := set.New[int]()
s2.Add(3, 4, 5)

symmetricDifference := s1.SymmetricDifference(s2)  // 1, 2, 4, 5

func (*Set[T]) Union

func (s *Set[T]) Union(set *Set[T]) *Set[T]

Union returns a new set with all the items in both sets. This is useful when you want to merge two sets into a new one. Note that the result set will not have any duplicate items, even if the input sets do.

Example usage:

s1 := set.New[int]()
s1.Add(1, 2, 3)

s2 := set.New[int]()
s2.Add(3, 4, 5)

union := s1.Union(s2)  // union contains 1, 2, 3, 4, 5

Jump to

Keyboard shortcuts

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