mapo

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 20, 2024 License: MIT Imports: 5 Imported by: 0

README

Map Order

build-img pkg-img coverage-img

Is a custom implementation of a map in Go that maintains the order of keys as they are added

Features

  • Order Preservation: Keys are stored in the order they are added
  • Custom JSON Marshalling: Implements custom JSON marshalling and unmarshalling to ensure the order of keys is preserved when converting to and from JSON
  • Key Management: Provides methods to add, delete, and retrieve keys in their maintained order

Installation

Go version 1.21+

go get github.com/itcomusic/mapo

Usage

import (
    "fmt"

    "github.com/itcomusic/mapo"
)

func main() {
    m := mapo.New()
    m.Set("a", 1)
    m.Set("b", 2)
    m.Set("c", 3)
    
    fmt.Println(m.Keys()) // [a, b, c]
	
    value, ok := m.Get("a")
    fmt.Println(value, ok) // 1, true
    m.Delete("c")
    
    b, _ := json.Marshal(m)
    fmt.Println(string(b)) // {"a":1,"b":2}
    
    var m2 mapo.Map
    _ = json.Unmarshal(b, &m2)
    fmt.Println(m2.Keys()) // [a, b]
}

License

MIT License

Documentation

Overview

Package maporder provides a map that maintains the order of insertion.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Map

type Map struct {
	// contains filtered or unexported fields
}
Example
package main

import (
	"encoding/json"
	"fmt"

	"github.com/itcomusic/mapo"
)

func main() {
	m := mapo.New()
	m.Set("a", 1)
	m.Set("b", 2)
	m.Set("c", 3)

	fmt.Println(m.Keys()) // [a, b, c]
	value, ok := m.Get("a")
	fmt.Println(value, ok) // 1, true
	m.Delete("c")

	b, err := json.Marshal(m)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(b)) // {"a":1,"b":2}

	var m2 mapo.Map
	if err := json.Unmarshal(b, &m2); err != nil {
		panic(err)
	}
	fmt.Println(m2.Keys()) // [a, b]

}
Output:

[a b c]
1 true
{"a":1,"b":2}
[a b]

func New

func New() *Map

New creates a new Map.

func NewWithSize

func NewWithSize(cap int) *Map

NewWithSize creates a new Map with the given capacity.

func (*Map) Delete

func (m *Map) Delete(key string)

Delete deletes the key.

func (*Map) Get

func (m *Map) Get(key string) (any, bool)

Get returns the value associated with the key.

func (*Map) Keys

func (m *Map) Keys() []string

Keys returns the keys in the map.

func (*Map) MarshalJSON

func (m *Map) MarshalJSON() ([]byte, error)

func (*Map) Set

func (m *Map) Set(key string, value any)

Set sets the key to value.

If the key already exists, the order is not updated.

func (*Map) UnmarshalJSON

func (m *Map) UnmarshalJSON(b []byte) error

Jump to

Keyboard shortcuts

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