Find Tier Thresholds With sort.Search

Assert ascending monotonicity with sort.SliceIsSorted, then use sort.Search to match usage metrics against threshold tiers and handle overflows.

GoData Integrity

Code

gosnippet
42 lines
package main

import (
	"fmt"
	"sort"
)

type Tier struct {
	MaxUnits int
	Price    int
}

func lookupTier(tiers []Tier, units int) (Tier, bool) {
	if !sort.SliceIsSorted(tiers, func(i, j int) bool {
		return tiers[i].MaxUnits < tiers[j].MaxUnits
	}) {
		panic("tier thresholds must be sorted ascending")
	}
	idx := sort.Search(len(tiers), func(i int) bool {
		return tiers[i].MaxUnits >= units
	})
	if idx == len(tiers) {
		return Tier{}, false
	}
	return tiers[idx], true
}

func main() {
	tiers := []Tier{
		{MaxUnits: 100, Price: 10},
		{MaxUnits: 500, Price: 8},
		{MaxUnits: 2000, Price: 5},
	}
	for _, usage := range []int{0, 100, 101, 1500, 2500} {
		tier, ok := lookupTier(tiers, usage)
		if !ok {
			fmt.Printf("usage=%d -> enterprise quote (above %d)\n", usage, tiers[len(tiers)-1].MaxUnits)
			continue
		}
		fmt.Printf("usage=%d -> cap=%d unit_price=%d\n", usage, tier.MaxUnits, tier.Price)
	}
}

Annotated execution — Find Tier Thresholds With sort.Search

Core state mutations happen within functions lookupTier and main.

Repetition is confined to for _, usage := range []int{0, 100, 101, 1500, 2500} — the rest of the file is straight-line.

Points of care

  • Installation step omitted because stock platform libraries provide every call.

Applying it

The entry-point signature is func lookupTier(tiers []Tier, units int) (Tier, bool)

Logged stdout lines show tags — usage= — when the file runs.

Launch the file; main takes over and steps through lookupTier.

Statements that matter

for _, usage := range []int{0, 100, 101, 1500, 2500} {
	tier, ok := lookupTier(tiers, usage)
	if !ok {
		fmt.Printf("usage=%d -> enterprise quote (above %d)\n", usage, tiers[len(tiers)-1].MaxUnits)
		continue
	}
	fmt.Printf("usage=%d -> cap=%d unit_price=%d\n", usage, tier.MaxUnits, tier.Price)
}
return Tier{}, false
panic("tier thresholds must be sorted ascending")

Interactive Tools for This Topic

FAQ

What does Find Tier Thresholds With sort.Search print when run?
Execute the whole file; each printed line is prefixed with a label like `usage=`.