Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

gnomod.toml

module = "gno.land/p/nym-moultest123/kit/tally/v0"
gno = "0.9"

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 186404
  max_deposit = "6000000ugnot"

tally.gno

// Package tally orders a scoreboard: highest score first, ties broken by key.
//
// Sixteen realms in this repo carry their own sort.Interface triple, because
// gno has no sort.Slice and every leaderboard therefore needs a named type
// with Len, Less and Swap. Eight of them rank on ONE score and then break the
// tie, which is what this package is; the rest rank on two scores and keep
// their own comparator. They do not agree on what happens at a tie, and one of
// them does not break ties at all.
//
// # The tie-break is the point
//
// A Render that reshuffles between identical calls is a bug, so the final
// comparison must be a total order. Comparing the score again (as
// r/moul/x/daily/rpgroom's third clause does) is not one: two rows with equal
// scores compare false in both directions, and their order then falls out of
// whatever the sort algorithm did with the input, which is reproducible but
// nobody chose it. [Sort] always ends on the key, so equal scores render in a
// stable, explicable order.
//
// # What is not here
//
// Storage: the caller keeps its own avl tree and maps it to [Entry]. That is
// what makes this adoptable by realms that already have their state, and
// [Board] is for new ones that do not.
//
// Rendering: a podium and a table already have an owner in
// [p/moul/kit/ui](/p/nym-moultest123/kit/ui/v0).
package tally

import (
	"sort"

	"gno.land/p/nt/avl/v0"
)

// Entry is one row of a scoreboard: an opaque key and its score.
//
// Key is whatever the caller ranks by, usually an address in its String form.
// It is the tie-break, so it must be unique within one board.
type Entry struct {
	Key   string
	Score int64
}

type byScore []Entry

func (e byScore) Len() int      { return len(e) }
func (e byScore) Swap(i, j int) { e[i], e[j] = e[j], e[i] }
func (e byScore) Less(i, j int) bool {
	if e[i].Score != e[j].Score {
		return e[i].Score > e[j].Score
	}
	return e[i].Key < e[j].Key
}

// Sort orders entries in place: highest score first, ties by key ascending.
func Sort(entries []Entry) { sort.Sort(byScore(entries)) }

// Top returns the n highest entries, sorted. A n at or below zero returns
// nothing; a n past the end returns everything. The input is not modified.
func Top(entries []Entry, n int) []Entry {
	if n <= 0 || len(entries) == 0 {
		return nil
	}
	out := make([]Entry, len(entries))
	copy(out, entries)
	Sort(out)
	if n > len(out) {
		n = len(out)
	}
	return out[:n]
}

// Rank returns the 1-based position of key once entries are sorted, or 0 if
// the key is absent. Equal scores still get distinct ranks, decided by the
// same key tie-break Sort uses, so no two rows ever claim the same place.
func Rank(entries []Entry, key string) int {
	sorted := make([]Entry, len(entries))
	copy(sorted, entries)
	Sort(sorted)
	for i, e := range sorted {
		if e.Key == key {
			return i + 1
		}
	}
	return 0
}

// Board is a scoreboard that owns its storage, for a realm that does not
// already have one. It is backed by a tree rather than a map: gno map
// iteration order is unspecified, and a Render built on one is not
// reproducible.
type Board struct {
	scores *avl.Tree // key -> int64
}

// NewBoard returns an empty Board.
func NewBoard() *Board { return &Board{scores: avl.NewTree()} }

// Add increases key's score by delta, which may be negative, and returns the
// new score. A key that was absent starts at zero.
func (b *Board) Add(key string, delta int64) int64 {
	n := b.Score(key) + delta
	b.scores.Set(key, n)
	return n
}

// Set replaces key's score outright.
func (b *Board) Set(key string, score int64) { b.scores.Set(key, score) }

// Score returns key's score, or zero if it has none. It does not distinguish
// an absent key from one scoring zero; use [Board.Has] when that matters.
func (b *Board) Score(key string) int64 {
	v := b.scores.Get(key)
	if v == nil {
		return 0
	}
	return v.(int64)
}

// Has reports whether key has been scored at all.
func (b *Board) Has(key string) bool { return b.scores.Get(key) != nil }

// Remove drops key, reporting whether it was there.
func (b *Board) Remove(key string) bool {
	_, removed := b.scores.Remove(key)
	return removed
}

// Len is the number of scored keys.
func (b *Board) Len() int { return b.scores.Size() }

// Entries returns every row, sorted by [Sort].
func (b *Board) Entries() []Entry {
	out := make([]Entry, 0, b.scores.Size())
	b.scores.Iterate("", "", func(k string, v any) bool {
		out = append(out, Entry{Key: k, Score: v.(int64)})
		return false
	})
	Sort(out)
	return out
}

// Top returns the n highest rows, sorted.
func (b *Board) Top(n int) []Entry { return Top(b.Entries(), n) }

// Rank returns key's 1-based position, or 0 if it is not on the board.
func (b *Board) Rank(key string) int {
	if !b.Has(key) {
		return 0
	}
	return Rank(b.Entries(), key)
}

tally_test.gno

package tally

import (
	"testing"

	"gno.land/p/nt/uassert/v0"
)

func keys(entries []Entry) string {
	out := ""
	for i, e := range entries {
		if i > 0 {
			out += ","
		}
		out += e.Key
	}
	return out
}

func TestSortOrdersByScoreThenKey(t *testing.T) {
	cases := []struct {
		name string
		in   []Entry
		want string
	}{
		{"already ordered", []Entry{{"a", 3}, {"b", 2}, {"c", 1}}, "a,b,c"},
		{"reversed", []Entry{{"c", 1}, {"b", 2}, {"a", 3}}, "a,b,c"},
		{"all tied, key decides", []Entry{{"c", 5}, {"a", 5}, {"b", 5}}, "a,b,c"},
		{"partial tie", []Entry{{"z", 1}, {"b", 9}, {"a", 9}}, "a,b,z"},
		{"negatives sort below", []Entry{{"a", -1}, {"b", 0}, {"c", 1}}, "c,b,a"},
		{"single", []Entry{{"only", 7}}, "only"},
		{"empty", nil, ""},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			in := make([]Entry, len(tc.in))
			copy(in, tc.in)
			Sort(in)
			uassert.Equal(t, tc.want, keys(in))
		})
	}
}

// TestSortIsATotalOrder is the defect this package exists to remove. A
// comparator whose last clause repeats the score (rpgroom's third clause) is
// not a total order: two equal rows compare false both ways and their order is
// decided by the algorithm. Sorting twice from different inputs must agree.
func TestSortIsATotalOrder(t *testing.T) {
	a := []Entry{{"x", 5}, {"y", 5}, {"z", 5}, {"w", 9}}
	b := []Entry{{"z", 5}, {"w", 9}, {"y", 5}, {"x", 5}}
	Sort(a)
	Sort(b)
	uassert.Equal(t, keys(a), keys(b))
	uassert.Equal(t, "w,x,y,z", keys(a))
}

func TestTop(t *testing.T) {
	in := []Entry{{"c", 1}, {"a", 3}, {"b", 2}}
	uassert.Equal(t, "a,b", keys(Top(in, 2)))
	uassert.Equal(t, "a,b,c", keys(Top(in, 10)))
	uassert.Equal(t, "", keys(Top(in, 0)))
	uassert.Equal(t, "", keys(Top(in, -1)))
	uassert.Equal(t, "", keys(Top(nil, 3)))
}

// TestTopDoesNotDisturbTheCaller pins that Top copies. A realm that renders a
// Top(3) and then iterates its own slice must not find it reordered.
func TestTopDoesNotDisturbTheCaller(t *testing.T) {
	in := []Entry{{"c", 1}, {"a", 3}, {"b", 2}}
	_ = Top(in, 2)
	uassert.Equal(t, "c,a,b", keys(in))
}

func TestRank(t *testing.T) {
	in := []Entry{{"c", 1}, {"a", 3}, {"b", 2}}
	uassert.Equal(t, 1, Rank(in, "a"))
	uassert.Equal(t, 2, Rank(in, "b"))
	uassert.Equal(t, 3, Rank(in, "c"))
	uassert.Equal(t, 0, Rank(in, "absent"))
}

// TestRankNeverTies is what makes a rendered "#3" mean something: two equal
// scores still get 2 and 3, never 2 and 2.
func TestRankNeverTies(t *testing.T) {
	in := []Entry{{"a", 5}, {"b", 5}, {"c", 5}}
	seen := map[int]bool{}
	for _, e := range in {
		r := Rank(in, e.Key)
		if seen[r] {
			t.Errorf("rank %d claimed twice", r)
		}
		seen[r] = true
	}
	uassert.Equal(t, 3, len(seen))
}

func TestBoardAddAndScore(t *testing.T) {
	b := NewBoard()
	uassert.Equal(t, 0, b.Len())
	uassert.Equal(t, int64(5), b.Add("a", 5))
	uassert.Equal(t, int64(8), b.Add("a", 3))
	uassert.Equal(t, int64(6), b.Add("a", -2))
	uassert.Equal(t, int64(6), b.Score("a"))
	uassert.Equal(t, int64(0), b.Score("never"))
	uassert.Equal(t, 1, b.Len())
}

func TestBoardHasDistinguishesAbsentFromZero(t *testing.T) {
	b := NewBoard()
	b.Set("zero", 0)
	uassert.True(t, b.Has("zero"))
	uassert.False(t, b.Has("absent"))
	uassert.Equal(t, int64(0), b.Score("zero"))
	uassert.Equal(t, int64(0), b.Score("absent"))
}

func TestBoardRemove(t *testing.T) {
	b := NewBoard()
	b.Set("a", 1)
	uassert.True(t, b.Remove("a"))
	uassert.False(t, b.Remove("a"))
	uassert.Equal(t, 0, b.Len())
}

func TestBoardEntriesAndTop(t *testing.T) {
	b := NewBoard()
	b.Set("c", 1)
	b.Set("a", 3)
	b.Set("b", 3)
	uassert.Equal(t, "a,b,c", keys(b.Entries()))
	uassert.Equal(t, "a,b", keys(b.Top(2)))
	uassert.Equal(t, 1, b.Rank("a"))
	uassert.Equal(t, 2, b.Rank("b"))
	uassert.Equal(t, 0, b.Rank("absent"))
}

// TestBoardOrderDoesNotDependOnInsertion is the reason Board is backed by a
// tree and not a map: the same scores inserted in a different order must
// render identically.
func TestBoardOrderDoesNotDependOnInsertion(t *testing.T) {
	one := NewBoard()
	for _, e := range []Entry{{"a", 5}, {"b", 5}, {"c", 9}} {
		one.Set(e.Key, e.Score)
	}
	two := NewBoard()
	for _, e := range []Entry{{"c", 9}, {"b", 5}, {"a", 5}} {
		two.Set(e.Key, e.Score)
	}
	uassert.Equal(t, keys(one.Entries()), keys(two.Entries()))
	uassert.Equal(t, "c,a,b", keys(one.Entries()))
}