xmap

package module
v1.0.0 Latest Latest
Warning

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

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

README

XContainer OrderedMap

English | 中文

XContainer OrderedMap is a Go implementation of an ordered map container that maintains the insertion order of key-value pairs while providing efficient lookup performance.

Features

  • Maintains insertion order of key-value pairs
  • Generic support for storing any comparable key type and any value type
  • Complete JSON serialization and deserialization support
  • Iterator support for traversal
  • Deep copy functionality
  • Thread-safe (requires external synchronization for concurrent access)

Installation

go get github.com/danielhookx/xcontainer/map

Usage Examples

Basic Operations
package main

import (
    "fmt"
    "github.com/danielhookx/xcontainer/map"
)

func main() {
    // Create a new ordered map
    m := xmap.NewOrderedMap[string, int]()

    // Add key-value pairs
    m.Set("first", 1)
    m.Set("second", 2)
    m.Set("third", 3)

    // Get value
    if value, exists := m.Get("second"); exists {
        fmt.Printf("Value: %d\n", value) // Output: Value: 2
    }

    // Delete key-value pair
    m.Delete("second")

    // Get length
    fmt.Printf("Length: %d\n", m.Len()) // Output: Length: 2
}
Iteration
func main() {
    m := xmap.NewOrderedMap[string, string]()
    m.Set("name", "Alice")
    m.Set("age", "25")
    m.Set("city", "Beijing")

    // Iterate using the iterator
    for k, v := range m.Iter() {
        fmt.Printf("%s: %s\n", k, v)
    }
    // Output:
    // name: Alice
    // age: 25
    // city: Beijing
}
JSON Serialization
func main() {
    m := xmap.NewOrderedMap[string, interface{}]()
    m.Set("name", "Bob")
    m.Set("age", 30)
    m.Set("hobbies", []string{"reading", "gaming"})

    // Serialize to JSON
    jsonData, err := json.Marshal(m)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(jsonData))
    // Output: {"name":"Bob","age":30,"hobbies":["reading","gaming"]}

    // Deserialize from JSON
    newMap := xmap.NewOrderedMap[string, interface{}]()
    if err := json.Unmarshal(jsonData, newMap); err != nil {
        log.Fatal(err)
    }
}
Deep Copy
func main() {
    m := xmap.NewOrderedMap[string, int]()
    m.Set("a", 1)
    m.Set("b", 2)

    // Create a deep copy
    m2 := m.Copy()
    
    // Modifying the original map won't affect the copy
    m.Set("c", 3)
    fmt.Println(m2.Len()) // Output: 2
}

API Reference

Main Methods
  • NewOrderedMap[K comparable, V any]() *OrderedMap[K, V] - Creates a new ordered map
  • Get(key K) (V, bool) - Retrieves a value by key
  • Set(key K, value V) bool - Sets a key-value pair
  • Delete(key K) bool - Removes a key-value pair
  • Len() int - Returns the number of key-value pairs
  • Copy() *OrderedMap[K, V] - Creates a deep copy
  • ToArray() []V - Returns all values in order
  • Iter() iter.Seq2[K, V] - Returns an iterator
  • MarshalJSON() ([]byte, error) - Serializes to JSON
  • UnmarshalJSON(data []byte) error - Deserializes from JSON

Notes

  1. This implementation is not thread-safe and requires external synchronization for concurrent access
  2. Key types must be comparable
  3. All keys are converted to strings during JSON serialization
  4. The iterator directly uses the underlying linked list for iteration, which means modifications during iteration will be reflected in the current iteration

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type MapNode

type MapNode[K comparable, V any] struct {
	K K
	V V
}

MapNode represents a key-value pair in the OrderedMap.

type OrderedMap

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

OrderedMap is a map that preserves the order of key-value pairs. It combines a map for fast lookups and a linked list for order preservation.

func NewOrderedMap

func NewOrderedMap[K comparable, V any]() *OrderedMap[K, V]

NewOrderedMap creates and initializes a new OrderedMap.

func (*OrderedMap[K, V]) Copy

func (m *OrderedMap[K, V]) Copy() *OrderedMap[K, V]

Copy creates a deep copy of the OrderedMap.

func (*OrderedMap[K, V]) Delete

func (m *OrderedMap[K, V]) Delete(key K) bool

Delete removes a key-value pair from the map. Returns true if the key was found and removed, false otherwise.

func (*OrderedMap[K, V]) Get

func (m *OrderedMap[K, V]) Get(key K) (V, bool)

Get retrieves a value from the map by key. Returns the value and a boolean indicating whether the key was found.

func (*OrderedMap[K, V]) Iter

func (m *OrderedMap[K, V]) Iter() iter.Seq2[K, V]

Iter returns an iterator that yields key-value pairs in insertion order. The iterator directly uses the underlying linked list for iteration.

func (*OrderedMap[K, V]) Len

func (m *OrderedMap[K, V]) Len() int

Len returns the number of key-value pairs in the map.

func (*OrderedMap[K, V]) MarshalJSON

func (m *OrderedMap[K, V]) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface. It serializes an OrderedMap into a JSON object, preserving the order of keys.

func (*OrderedMap[K, V]) Set

func (m *OrderedMap[K, V]) Set(key K, value V) bool

Set adds or updates a key-value pair in the map. Returns true if the key is new, false if it already existed.

func (*OrderedMap[K, V]) ToArray

func (m *OrderedMap[K, V]) ToArray() []V

ToArray returns all values in the map as a slice, preserving the order.

func (*OrderedMap[K, V]) UnmarshalJSON

func (m *OrderedMap[K, V]) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface. It deserializes a JSON object into an OrderedMap, preserving the order of keys.

Jump to

Keyboard shortcuts

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