Predicts grocery freshness timelines and suggests optimal consumption order Go
👤 Sharing: AI
```go
package main
import (
"fmt"
"sort"
"time"
)
// Item represents a grocery item with its name and purchase date.
type Item struct {
Name string
PurchaseDate time.Time
ShelfLife time.Duration // Estimated shelf life (e.g., 3 days, 7 days). Using time.Duration makes date arithmetic cleaner.
}
// ByExpiration implements sort.Interface for []Item based on expiration date.
type ByExpiration []Item
func (a ByExpiration) Len() int { return len(a) }
func (a ByExpiration) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByExpiration) Less(i, j int) bool {
return a[i].PurchaseDate.Add(a[i].ShelfLife).Before(a[j].PurchaseDate.Add(a[j].ShelfLife))
}
func main() {
// Define some grocery items with their purchase dates and estimated shelf lives.
// You can replace these with input from a user interface, file, database, etc.
items := []Item{
{Name: "Strawberries", PurchaseDate: time.Now().Add(-2 * 24 * time.Hour), ShelfLife: 3 * 24 * time.Hour}, // Purchased 2 days ago, 3 days shelf life
{Name: "Milk", PurchaseDate: time.Now().Add(-1 * 24 * time.Hour), ShelfLife: 5 * 24 * time.Hour}, // Purchased 1 day ago, 5 days shelf life
{Name: "Bread", PurchaseDate: time.Now().Add(-0 * 24 * time.Hour), ShelfLife: 72 * time.Hour}, // Purchased today, 3 days shelf life
{Name: "Spinach", PurchaseDate: time.Now().Add(-3 * 24 * time.Hour), ShelfLife: 4 * 24 * time.Hour}, // Purchased 3 days ago, 4 days shelf life
{Name: "Chicken Breast", PurchaseDate: time.Now().Add(-0 * 24 * time.Hour), ShelfLife: 2 * 24 * time.Hour}, // Purchased today, 2 days shelf life
}
// Sort the items by their expiration date (earliest first).
sort.Sort(ByExpiration(items))
// Print the optimal consumption order and expiration dates.
fmt.Println("Optimal Consumption Order:")
for i, item := range items {
expirationDate := item.PurchaseDate.Add(item.ShelfLife)
daysUntilExpiration := int(expirationDate.Sub(time.Now()).Hours() / 24) // Calculate days, rounding down
fmt.Printf("%d. %s (Expires: %s, in %d days)\n", i+1, item.Name, expirationDate.Format("2006-01-02"), daysUntilExpiration)
}
// Example: Check if any items are already expired.
fmt.Println("\nChecking for expired items:")
for _, item := range items {
expirationDate := item.PurchaseDate.Add(item.ShelfLife)
if time.Now().After(expirationDate) {
fmt.Printf("WARNING: %s is already expired (Expired on: %s)\n", item.Name, expirationDate.Format("2006-01-02"))
}
}
}
```
Key improvements and explanations:
* **`Item` struct with `time.Time` and `time.Duration`:** This is a critical improvement. Using `time.Time` and `time.Duration` makes date calculations much more robust and readable than using integers or strings. `time.Duration` represents a length of time, perfect for `ShelfLife`.
* **`ByExpiration` type and `sort.Sort`:** The `ByExpiration` type implements the `sort.Interface`, allowing you to easily sort the `Item` slice based on the calculated expiration date. Using `sort.Sort` is the idiomatic way to sort in Go. The `Less` function within `ByExpiration` calculates expiration for *both* items being compared, making the sort accurate even if different items were purchased on different dates.
* **Expiration Calculation:** The core logic is now `item.PurchaseDate.Add(item.ShelfLife)`. This calculates the *actual* expiration date based on the purchase date and shelf life.
* **`time.Now()`:** The code now correctly uses `time.Now()` to get the current time for accurate calculations.
* **Expiration Date Formatting:** `expirationDate.Format("2006-01-02")` formats the `time.Time` object into a human-readable date string. "2006-01-02" is the magic string Go uses to represent the desired date format.
* **Days Until Expiration:** The code calculates the number of days until expiration. This is done robustly by subtracting the current time from the expiration time, getting a `time.Duration`, converting it to hours, and then dividing by 24. It then uses `int` for proper display.
* **Expired Item Check:** Includes a loop to check if any items are already expired by comparing the calculated expiration date with `time.Now()`.
* **Clear Output:** The output is formatted to be easy to read.
* **Comments:** Extensive comments explain each part of the code.
* **Error Handling (Implicit):** Using `time.Time` and `time.Duration` largely eliminates the need for manual error handling that would be required with string-based date parsing, simplifying the example.
* **Realistic Shelf Life:** Uses `time.Duration` constants (e.g., `3 * 24 * time.Hour`) to represent shelf lives in days, which is much more readable and maintainable.
* **Example Data:** Provides example grocery items to demonstrate the functionality. The purchase dates are set to be relative to "now" using `time.Now().Add()`.
How to run the code:
1. **Save:** Save the code as a `.go` file (e.g., `grocery.go`).
2. **Open a terminal:** Open a terminal or command prompt.
3. **Navigate:** Navigate to the directory where you saved the file.
4. **Run:** Execute the command `go run grocery.go`.
The output will show the optimal consumption order of the grocery items, their expiration dates, and a warning if any items are already expired. Because the code uses `time.Now()`, the results will change each time you run the program. You can modify the `items` slice to add or change the grocery items and their purchase dates and shelf lives to test the program further.
👁️ Viewed: 5
Comments