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.
Code
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
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.Binary Text ConverterConvert UTF-8 text to 8-bit binary groups and decode binary back to text with strict validation.Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.
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=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.