Group stock by how soon it expires
A food depot dashboard puts every batch into one of four buckets so staff can see what to move first.
- Below zero days is "expired"; 0 to 7 is "week"; 8 to 30 is "month"; anything more is "later".
- All four keys appear in the result, even when the count is zero.
expiryBuckets(daysLeft: list<int>) → map<string, int>
Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
func expiryBuckets(daysLeft []int) map[string]int {
}
Worked examples
| Call | Result |
|---|---|
expiryBuckets([]int{-1, 0, 7, 8, 30, 31, 400}) | map[string]int{"expired": 1, "week": 2, "month": 2, "later": 2} |
expiryBuckets([]int{}) | map[string]int{"expired": 0, "week": 0, "month": 0, "later": 0} |
expiryBuckets([]int{-5, -5, -5}) | map[string]int{"expired": 3, "week": 0, "month": 0, "later": 0} |
expiryBuckets([]int{0}) | map[string]int{"expired": 0, "week": 1, "month": 0, "later": 0} |
Hint
Seed the map with all four keys at zero first, then walk the list once.
Reference solution in Go
func expiryBuckets(daysLeft []int) map[string]int {
out := map[string]int{"expired": 0, "week": 0, "month": 0, "later": 0}
for _, d := range daysLeft {
switch {
case d < 0:
out["expired"]++
case d <= 7:
out["week"]++
case d <= 30:
out["month"]++
default:
out["later"]++
}
}
return out
}