File: example_test.go

package info (click to toggle)
golang-github-wk8-go-ordered-map 2.1.8-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 196 kB
  • sloc: makefile: 22
file content (67 lines) | stat: -rw-r--r-- 1,440 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package orderedmap_test

import (
	"encoding/json"
	"fmt"

	"github.com/wk8/go-ordered-map/v2"
)

func Example() {
	om := orderedmap.New[string, string](3)

	om.Set("foo", "bar")
	om.Set("bar", "baz")
	om.Set("coucou", "toi")

	fmt.Println("## Get operations: ##")
	fmt.Println(om.Get("foo"))
	fmt.Println(om.Get("i dont exist"))
	fmt.Println(om.Value("coucou"))

	fmt.Println("## Iterating over pairs from oldest to newest: ##")
	for pair := om.Oldest(); pair != nil; pair = pair.Next() {
		fmt.Printf("%s => %s\n", pair.Key, pair.Value)
	}

	fmt.Println("## Iterating over the 2 newest pairs: ##")
	i := 0
	for pair := om.Newest(); pair != nil; pair = pair.Prev() {
		fmt.Printf("%s => %s\n", pair.Key, pair.Value)
		i++
		if i >= 2 {
			break
		}
	}

	fmt.Println("## JSON serialization: ##")
	data, err := json.Marshal(om)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(data))

	fmt.Println("## JSON deserialization: ##")
	om2 := orderedmap.New[string, string]()
	if err := json.Unmarshal(data, &om2); err != nil {
		panic(err)
	}
	fmt.Println(om2.Oldest().Key)

	// Output:
	// ## Get operations: ##
	// bar true
	//  false
	// toi
	// ## Iterating over pairs from oldest to newest: ##
	// foo => bar
	// bar => baz
	// coucou => toi
	// ## Iterating over the 2 newest pairs: ##
	// coucou => toi
	// bar => baz
	// ## JSON serialization: ##
	// {"foo":"bar","bar":"baz","coucou":"toi"}
	// ## JSON deserialization: ##
	// foo
}