Search Apps Documentation Source Content File Folder Download Copy Actions Download State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

orderedmapdemo.gno

2.08 Kb · 65 lines
 1// Package orderedmapdemo is a small gnoweb demo of the insertion-ordered map
 2// provided by the [p/moul/x/daily/orderedmap](/p/moul/x/daily/orderedmap/v0)
 3// library: it shows that order survives updates and deletes.
 4//
 5// It contains no map logic of its own. Stateless, so Render is deterministic —
 6// which is precisely what the library is for.
 7package orderedmapdemo
 8
 9import (
10	"strconv"
11	"strings"
12
13	"gno.land/p/moul/x/daily/orderedmap/v0"
14)
15
16// Render renders the demo for gnoweb.
17func Render(path string) string {
18	var b strings.Builder
19	b.WriteString("# Ordered Map\n\n")
20	b.WriteString("A map that remembers insertion order, demoing the ")
21	b.WriteString("[`p/moul/x/daily/orderedmap`](/p/moul/x/daily/orderedmap/v0) library.\n\n")
22
23	o := orderedmap.New()
24	for _, kv := range [][2]string{{"delta", "4"}, {"alpha", "1"}, {"charlie", "3"}, {"bravo", "2"}} {
25		o.Set(kv[0], kv[1])
26	}
27
28	b.WriteString("## Inserted\n\n")
29	b.WriteString("`delta, alpha, charlie, bravo` → order kept as inserted, **not** sorted:\n\n")
30	b.WriteString(table(o))
31
32	o.Set("alpha", "99")
33	b.WriteString("\n## After `Set(\"alpha\", \"99\")`\n\n")
34	b.WriteString("Updating keeps the original position — insertion order means *first* insertion:\n\n")
35	b.WriteString(table(o))
36
37	o.Delete("charlie")
38	o.Set("charlie", "new")
39	b.WriteString("\n## After deleting and re-adding `charlie`\n\n")
40	b.WriteString("Re-inserting is a **new** insertion, so it goes last:\n\n")
41	b.WriteString(table(o))
42
43	b.WriteString("\n> gno map iteration order is unspecified. A realm that ranges over a ")
44	b.WriteString("built-in map to build its page can emit a different page every call — ")
45	b.WriteString("a consensus bug, not a cosmetic one. This is the fix.\n")
46	return b.String()
47}
48
49func table(o *orderedmap.OrderedMap) string {
50	var b strings.Builder
51	b.WriteString("| # | key | value |\n|---|---|---|\n")
52	i := 0
53	o.Iterate(func(k, v string) bool {
54		i++
55		b.WriteString("| ")
56		b.WriteString(strconv.Itoa(i))
57		b.WriteString(" | `")
58		b.WriteString(k)
59		b.WriteString("` | `")
60		b.WriteString(v)
61		b.WriteString("` |\n")
62		return false
63	})
64	return b.String()
65}