utils

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Mar 8, 2025 License: MIT Imports: 7 Imported by: 0

README

Utility Package

This package provides utility functions and tools for data structure implementations in Go. It includes iterators, serialization helpers, and data structure converters.

Features

Iterators
  • Generic iterator interface with HasNext(), Next(), and Reset() methods
  • Implementations for different data structures:
    • SliceIterator: For array/slice iteration
    • MapIterator: For map iteration with optional key ordering
    • LinkedListIterator: For linked list traversal
    • TreeIterator: For tree traversal with multiple orders (PreOrder, InOrder, PostOrder, LevelOrder)
Serialization
  • Support for multiple formats:
    • JSON serialization with pretty print option
    • XML serialization with pretty print option
    • GOB serialization for Go-specific binary format
  • Helper functions for string serialization/deserialization
  • Deep copy functionality using serialization
Type Converters
  • Array/Slice conversions:
    • ArrayToSet: Convert array to set
    • SetToArray: Convert set to array
    • ArrayToSortedArray: Sort array of orderable types
    • ArrayToFrequencyMap: Create frequency map from array
    • ArrayToMatrix: Convert 1D array to 2D matrix
  • Data structure conversions:
    • ArrayToLinkedList: Convert array to linked list
    • LinkedListToArray: Convert linked list to array
    • ArrayToBinaryTree: Convert array to binary tree (level-order)
    • BinaryTreeToArray: Convert binary tree to array (level-order)
  • Map conversions:
    • MapToArray: Convert map to array of key-value pairs
    • ArrayToMap: Convert array of key-value pairs to map

Usage Examples

Iterator Usage
// Slice Iterator
numbers := []int{1, 2, 3, 4, 5}
iter := NewSliceIterator(numbers)
for iter.HasNext() {
    value := iter.Next()
    // Process value
}

// Map Iterator
myMap := map[string]int{"a": 1, "b": 2}
mapIter := NewMapIterator(myMap, nil)
for mapIter.HasNext() {
    key, value := mapIter.Next()
    // Process key-value pair
}

// Tree Iterator with different traversal orders
treeIter := NewTreeIterator(root, InOrder)
for treeIter.HasNext() {
    value := treeIter.Next()
    // Process value
}
Serialization Usage
// JSON Serialization
jsonSerializer := JSONSerializer{PrettyPrint: true}
data := MyStruct{...}
bytes, err := jsonSerializer.Serialize(data)

// Using SerializationHelper
helper := NewSerializationHelper(FormatJSON, true)
str, err := helper.Serialize(data)

// Deep Copy
src := MyStruct{...}
var dst MyStruct
err := DeepCopy(&src, &dst)
Converter Usage
// Array to Set conversion
arr := []int{1, 2, 2, 3, 3, 4}
set := ArrayToSet(arr)

// Array to Sorted Array
unsorted := []int{3, 1, 4, 1, 5, 9}
sorted := ArrayToSortedArray(unsorted)

// Array to Binary Tree
arr := []int{1, 2, 3, 4, 5}
tree := ArrayToBinaryTree(arr)

// Matrix conversions
matrix := ArrayToMatrix([]int{1, 2, 3, 4, 5, 6}, 3)
array := MatrixToArray(matrix)

Implementation Details

Generic Support
  • All implementations use Go generics for type safety
  • Type constraints:
    • comparable for map keys and set elements
    • orderable for sortable types
    • any for general purpose use
Performance Considerations
  • Efficient implementations focusing on minimal allocations
  • Appropriate data structure choices for different operations
  • Optimized algorithms for common operations

Testing

Each component comes with comprehensive test coverage. Run tests using:

go test ./...

Contributing

Contributions are welcome! Please ensure that any new features or modifications come with:

  • Proper documentation
  • Comprehensive test cases
  • Example usage
  • Generic type support where applicable

License

This package is distributed under the MIT license. See the LICENSE file for more details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ArrayToFrequencyMap

func ArrayToFrequencyMap[T comparable](arr []T) map[T]int

ArrayToFrequencyMap converts an array to a frequency map

func ArrayToMap

func ArrayToMap[K comparable, V any](arr [][2]any) map[K]V

ArrayToMap converts an array of key-value pairs to a map

func ArrayToMatrix

func ArrayToMatrix[T any](arr []T, cols int) [][]T

ArrayToMatrix converts a 1D array to a 2D matrix with specified number of columns

func ArrayToSet

func ArrayToSet[T comparable](arr []T) map[T]struct{}

ArrayToSet converts an array to a set (map with empty struct values)

func ArrayToSortedArray

func ArrayToSortedArray[T orderable](arr []T) []T

ArrayToSortedArray converts an array to a sorted array

func BinaryTreeToArray

func BinaryTreeToArray[T any](root *TreeNode[T]) []T

BinaryTreeToArray converts a binary tree to its level-order array representation

func DeepCopy

func DeepCopy(src, dst interface{}) error

DeepCopy creates a deep copy of a value using serialization

func DeserializeFromString

func DeserializeFromString(data string, v interface{}, format SerializationFormat) error

DeserializeFromString deserializes data from a string in the specified format

func FrequencyMapToArray

func FrequencyMapToArray[T comparable](freq map[T]int) []T

FrequencyMapToArray converts a frequency map to an array with repeated elements

func LinkedListToArray

func LinkedListToArray[T any](head *Node[T]) []T

LinkedListToArray converts a singly linked list to an array

func MapToArray

func MapToArray[K comparable, V any](m map[K]V) [][2]any

MapToArray converts a map to an array of key-value pairs

func MatrixToArray

func MatrixToArray[T any](matrix [][]T) []T

MatrixToArray converts a 2D matrix to a 1D array

func RegisterTypes

func RegisterTypes()

RegisterTypes registers types for Gob serialization

func SerializeToString

func SerializeToString(v interface{}, format SerializationFormat, prettyPrint bool) (string, error)

SerializeToFile serializes data to a string in the specified format

func SetToArray

func SetToArray[T comparable](set map[T]struct{}) []T

SetToArray converts a set to an array

Types

type Any

type Any interface {
	any
}

Any represents any type

type Comparable

type Comparable interface {
	comparable
}

Comparable represents all comparable types

type ExampleStruct

type ExampleStruct struct {
	ID       int                    `json:"id" xml:"id"`
	Name     string                 `json:"name" xml:"name"`
	Tags     []string               `json:"tags" xml:"tags"`
	Metadata map[string]interface{} `json:"metadata" xml:"metadata"`
}

Example usage types

type GobSerializer

type GobSerializer struct{}

GobSerializer implements Gob serialization

func (GobSerializer) Deserialize

func (s GobSerializer) Deserialize(data []byte, v interface{}) error

func (GobSerializer) Serialize

func (s GobSerializer) Serialize(v interface{}) ([]byte, error)

type Iterator

type Iterator[T any] interface {
	HasNext() bool
	Next() T
	Reset()
}

Iterator interface defines the basic iterator operations

type JSONSerializer

type JSONSerializer struct {
	PrettyPrint bool
}

JSONSerializer implements JSON serialization

func (JSONSerializer) Deserialize

func (s JSONSerializer) Deserialize(data []byte, v interface{}) error

func (JSONSerializer) Serialize

func (s JSONSerializer) Serialize(v interface{}) ([]byte, error)

type LinkedListIterator

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

LinkedListIterator implements Iterator for linked lists

func NewLinkedListIterator

func NewLinkedListIterator[T any](head *Node[T]) *LinkedListIterator[T]

NewLinkedListIterator creates a new linked list iterator

func (*LinkedListIterator[T]) HasNext

func (it *LinkedListIterator[T]) HasNext() bool

func (*LinkedListIterator[T]) Next

func (it *LinkedListIterator[T]) Next() T

func (*LinkedListIterator[T]) Reset

func (it *LinkedListIterator[T]) Reset()

type MapIterator

type MapIterator[K comparable, V any] struct {
	// contains filtered or unexported fields
}

MapIterator implements Iterator for maps

func NewMapIterator

func NewMapIterator[K comparable, V any](data map[K]V, keyOrder func([]K)) *MapIterator[K, V]

NewMapIterator creates a new map iterator with optional key ordering function

func (*MapIterator[K, V]) HasNext

func (it *MapIterator[K, V]) HasNext() bool

func (*MapIterator[K, V]) Next

func (it *MapIterator[K, V]) Next() (K, V)

func (*MapIterator[K, V]) Reset

func (it *MapIterator[K, V]) Reset()

type Node

type Node[T any] struct {
	Value T
	Next  *Node[T]
}

ArrayToLinkedList converts an array to a singly linked list

func ArrayToLinkedList

func ArrayToLinkedList[T any](arr []T) *Node[T]

type Numeric

type Numeric interface {
	constraints.Integer | constraints.Float
}

Numeric represents all numeric types

type Ordered

type Ordered interface {
	constraints.Ordered
}

Ordered represents all ordered types

type SerializationFormat

type SerializationFormat string

SerializationFormat represents supported serialization formats

const (
	FormatJSON SerializationFormat = "json"
	FormatXML  SerializationFormat = "xml"
	FormatGOB  SerializationFormat = "gob"
)

type SerializationHelper

type SerializationHelper struct {
	Format      SerializationFormat
	PrettyPrint bool
}

SerializationHelper provides helper methods for common serialization tasks

func NewSerializationHelper

func NewSerializationHelper(format SerializationFormat, prettyPrint bool) *SerializationHelper

func (*SerializationHelper) Deserialize

func (h *SerializationHelper) Deserialize(data string, v interface{}) error

func (*SerializationHelper) Serialize

func (h *SerializationHelper) Serialize(v interface{}) (string, error)

type Serializer

type Serializer interface {
	Serialize(v interface{}) ([]byte, error)
	Deserialize(data []byte, v interface{}) error
}

Serializer interface defines methods for serialization and deserialization

func GetSerializer

func GetSerializer(format SerializationFormat, prettyPrint bool) (Serializer, error)

GetSerializer returns a serializer for the specified format

type SliceIterator

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

SliceIterator implements Iterator for slices

func NewSliceIterator

func NewSliceIterator[T any](data []T) *SliceIterator[T]

NewSliceIterator creates a new slice iterator

func (*SliceIterator[T]) HasNext

func (it *SliceIterator[T]) HasNext() bool

func (*SliceIterator[T]) Next

func (it *SliceIterator[T]) Next() T

func (*SliceIterator[T]) Reset

func (it *SliceIterator[T]) Reset()

type TraversalOrder

type TraversalOrder int

TreeIterator implements Iterator for binary trees with different traversal orders

const (
	PreOrder TraversalOrder = iota
	InOrder
	PostOrder
	LevelOrder
)

type TreeIterator

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

func NewTreeIterator

func NewTreeIterator[T any](root *TreeNode[T], order TraversalOrder) *TreeIterator[T]

NewTreeIterator creates a new tree iterator with specified traversal order

func (*TreeIterator[T]) HasNext

func (it *TreeIterator[T]) HasNext() bool

func (*TreeIterator[T]) Next

func (it *TreeIterator[T]) Next() T

func (*TreeIterator[T]) Reset

func (it *TreeIterator[T]) Reset()

type TreeNode

type TreeNode[T any] struct {
	Value T
	Left  *TreeNode[T]
	Right *TreeNode[T]
}

ArrayToBinaryTree converts a level-order array representation to a binary tree

func ArrayToBinaryTree

func ArrayToBinaryTree[T any](arr []T) *TreeNode[T]

type XMLSerializer

type XMLSerializer struct {
	PrettyPrint bool
}

XMLSerializer implements XML serialization

func (XMLSerializer) Deserialize

func (s XMLSerializer) Deserialize(data []byte, v interface{}) error

func (XMLSerializer) Serialize

func (s XMLSerializer) Serialize(v interface{}) ([]byte, error)

Jump to

Keyboard shortcuts

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