Drill

ProblemsTypeScript › inventory

Group stock by how soon it expires

mediuminventoryTypeScript

A food depot dashboard puts every batch into one of four buckets so staff can see what to move first.

expiryBuckets(daysLeft: list<int>) → map<string, int>

Solve it in the editor →

Where you start

function expiryBuckets(daysLeft: number[]): Record<string, number> {
  
}

Worked examples

CallResult
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 TypeScript
function expiryBuckets(daysLeft: number[]): Record<string, number> {
  const out: Record<string, number> = { 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;
}

The same problem in another language

More inventory problems in TypeScript