Problems › JavaScript › inventory
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>
Where you start
function expiryBuckets(daysLeft) {
}
Worked examples
| Call | Result |
|---|---|
expiryBuckets([-1,0,7,8,30,31,400]) | {"expired":1,"week":2,"month":2,"later":2} |
expiryBuckets([]) | {"expired":0,"week":0,"month":0,"later":0} |
expiryBuckets([-5,-5,-5]) | {"expired":3,"week":0,"month":0,"later":0} |
expiryBuckets([0]) | {"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 JavaScript
function expiryBuckets(daysLeft) {
const out = { expired: 0, week: 0, month: 0, later: 0 };
for (const d of daysLeft) {
if (d < 0) out.expired++;
else if (d <= 7) out.week++;
else if (d <= 30) out.month++;
else out.later++;
}
return out;
}