AI-Driven Virtual Shopping Assistant with Product Recommendation and Price Comparison JavaScript
👤 Sharing: AI
```javascript
// Mock Product Database (Replace with real API calls in a real application)
const products = [
{
id: 1,
name: "Laptop X1",
category: "Electronics",
price: 1200,
specs: { processor: "Intel i7", ram: "16GB", storage: "512GB SSD" },
imageUrl: "laptop_x1.jpg",
description: "Powerful laptop for professionals and gamers.",
availability: true,
vendor: "TechStore",
rating: 4.5,
reviews: [
{ user: "Alice", comment: "Great performance!", rating: 5 },
{ user: "Bob", comment: "A bit pricey, but worth it.", rating: 4 },
],
},
{
id: 2,
name: "Wireless Mouse M2",
category: "Electronics",
price: 25,
specs: { dpi: "1600", connectivity: "Bluetooth" },
imageUrl: "mouse_m2.jpg",
description: "Ergonomic wireless mouse for comfortable use.",
availability: true,
vendor: "AccessoryHub",
rating: 4.2,
reviews: [
{ user: "Charlie", comment: "Works perfectly.", rating: 5 },
{ user: "David", comment: "Good value for money.", rating: 4 },
],
},
{
id: 3,
name: "Running Shoes Z9",
category: "Clothing",
price: 80,
specs: { size: "10", color: "Black", material: "Mesh" },
imageUrl: "shoes_z9.jpg",
description: "Comfortable running shoes for daily workouts.",
availability: false, // Simulate out of stock
vendor: "SportsGear",
rating: 4.8,
reviews: [
{ user: "Eve", comment: "Very comfortable and lightweight.", rating: 5 },
{ user: "Frank", comment: "Great for running.", rating: 5 },
],
},
{
id: 4,
name: "Laptop Y2 (Alternative)",
category: "Electronics",
price: 1100,
specs: { processor: "AMD Ryzen 5", ram: "16GB", storage: "256GB SSD" },
imageUrl: "laptop_y2.jpg",
description: "Budget-friendly laptop for everyday tasks.",
availability: true,
vendor: "ValueTech",
rating: 4.0,
reviews: [
{ user: "Grace", comment: "Good for the price.", rating: 4 },
{ user: "Henry", comment: "A bit slow sometimes.", rating: 3 },
],
},
{
id: 5,
name: "Smart Watch W1",
category: "Electronics",
price: 200,
specs: { features: ["Heart rate monitor", "GPS", "Sleep tracking"] },
imageUrl: "watch_w1.jpg",
description: "Smart watch for fitness and notifications.",
availability: true,
vendor: "WearableTech",
rating: 4.6,
reviews: [
{ user: "Ivy", comment: "Excellent features.", rating: 5 },
{ user: "Jack", comment: "Battery life could be better.", rating: 4 },
],
},
];
// --------------------------------------------------------------------
// Helper Functions (Simulating AI & Recommendation Logic)
// --------------------------------------------------------------------
// Simple Keyword Matching for Product Search
function searchProducts(query) {
query = query.toLowerCase();
return products.filter(product =>
product.name.toLowerCase().includes(query) ||
product.category.toLowerCase().includes(query) ||
product.description.toLowerCase().includes(query)
);
}
// Basic Recommendation Engine (Based on category and rating)
function recommendProducts(userPreferences) {
const category = userPreferences.category; // Extract category preference. Assume only one for simplicity.
const minRating = userPreferences.minRating || 4.0; // Default minimum rating
return products.filter(product =>
product.category === category && product.rating >= minRating
).sort((a, b) => b.rating - a.rating); // Sort by rating (highest first)
}
// Price Comparison (Finds the lowest price for a given product name)
function comparePrices(productName) {
const similarProducts = products.filter(product =>
product.name.toLowerCase().includes(productName.toLowerCase())
);
if (similarProducts.length === 0) {
return "No similar products found for price comparison.";
}
let lowestPrice = Infinity;
let lowestPriceProduct = null;
similarProducts.forEach(product => {
if (product.price < lowestPrice) {
lowestPrice = product.price;
lowestPriceProduct = product;
}
});
if (lowestPriceProduct) {
return `The lowest price for a product like '${productName}' is $${lowestPrice} at ${lowestPriceProduct.vendor} (${lowestPriceProduct.name}).`;
} else {
return "Could not determine the lowest price.";
}
}
// Filter by Availability (example filter function)
function filterByAvailability(available) {
return products.filter(product => product.availability === available);
}
// --------------------------------------------------------------------
// Virtual Shopping Assistant Function
// --------------------------------------------------------------------
function virtualShoppingAssistant(userInput) {
userInput = userInput.toLowerCase();
// 1. Intent Recognition (Simplified using keyword matching)
if (userInput.includes("search")) {
const searchQuery = userInput.replace("search", "").trim(); // Extract search term
const searchResults = searchProducts(searchQuery);
if (searchResults.length > 0) {
return "Search results for '" + searchQuery + "':\n" +
searchResults.map(product => `- ${product.name} ($${product.price}) from ${product.vendor}`).join("\n");
} else {
return "No products found matching your search.";
}
} else if (userInput.includes("recommend")) {
// Simulate user preferences (In a real app, these would be gathered from the user)
const userPreferences = { category: "Electronics", minRating: 4.5 }; // Example preferences
const recommendations = recommendProducts(userPreferences);
if (recommendations.length > 0) {
return "Based on your preferences, I recommend:\n" +
recommendations.map(product => `- ${product.name} ($${product.price}) from ${product.vendor} (Rating: ${product.rating})`).join("\n");
} else {
return "No recommendations found based on your preferences.";
}
} else if (userInput.includes("price comparison") || userInput.includes("compare prices")) {
const productNameForComparison = userInput.replace(/price comparison|compare prices|for/g, "").trim();
return comparePrices(productNameForComparison);
} else if (userInput.includes("available") || userInput.includes("in stock")) {
const availableProducts = filterByAvailability(true);
if (availableProducts.length > 0) {
return "Available products:\n" + availableProducts.map(product => `- ${product.name} ($${product.price}) from ${product.vendor}`).join("\n");
} else {
return "No products currently in stock.";
}
}
else {
return "Sorry, I didn't understand your request. Try 'search', 'recommend', or 'price comparison'.";
}
}
// --------------------------------------------------------------------
// Example Usage (Simulating user interaction)
// --------------------------------------------------------------------
console.log(virtualShoppingAssistant("search laptop"));
console.log("\n");
console.log(virtualShoppingAssistant("recommend me something"));
console.log("\n");
console.log(virtualShoppingAssistant("price comparison for laptop")); // Changed to a more general name
console.log("\n");
console.log(virtualShoppingAssistant("What is available?"));
console.log("\n");
console.log(virtualShoppingAssistant("I want to buy shoes"));
console.log("\n");
console.log(virtualShoppingAssistant("Compare prices for mouse"));
```
Key improvements and explanations:
* **Clear Structure:** The code is now well-structured with comments separating different sections: mock data, helper functions, the main assistant function, and example usage. This makes it much easier to understand and maintain.
* **Mock Data:** Uses a `products` array as a mock database. In a real application, this would be replaced by API calls to a real e-commerce platform or database. The mock data includes more varied product information (vendor, rating, reviews, availability, image URLs, descriptions, etc.) for richer scenarios.
* **Helper Functions:**
* `searchProducts(query)`: Performs a simple keyword-based search across product name, category, and description. Case-insensitive.
* `recommendProducts(userPreferences)`: Simulates a basic recommendation engine. It filters products based on user category preference and a minimum rating. Critically, it now sorts the results by rating, showing the highest-rated products first. Takes `userPreferences` as an argument, allowing for more flexible recommendation logic.
* `comparePrices(productName)`: Finds the lowest price for a product with a similar name. Improved to handle cases where no similar products are found. Now finds the *actual* lowest price among similar products and includes the vendor name.
* `filterByAvailability(available)`: Returns products that are in stock or out of stock, based on the `available` boolean parameter.
* **`virtualShoppingAssistant(userInput)` Function:**
* **Intent Recognition:** Uses simple `includes()` checks to determine the user's intent (search, recommendation, price comparison). A real application would use a more sophisticated NLP (Natural Language Processing) technique for intent recognition.
* **Clearer Responses:** The responses from the assistant are now more informative and user-friendly. They include product names, prices, and vendor names.
* **Error Handling:** Basic error handling is included for cases where no products are found or recommendations cannot be made.
* **Parameter extraction**: Extracts the search query, product name for comparison, etc., from the user input using `replace()` and `trim()` to clean up the input.
* **Example Usage:** Demonstrates how to use the `virtualShoppingAssistant()` function with different user inputs.
* **Realistic Simulation:** The code tries to simulate some aspects of a real e-commerce application, such as:
* Product availability (some products are out of stock).
* Product ratings and reviews.
* Different vendors selling similar products.
* **Modularity:** The code is designed to be modular, making it easier to add new features or modify existing ones. For instance, you can add new filter functions easily.
* **Comments:** Extensive comments explain the purpose of each section of the code.
* **Realistic User Input Handling:** The assistant now better handles variations in user input for price comparisons (e.g., "price comparison for laptop", "compare prices for mouse").
How to Run:
1. **Save:** Save the code as a `.js` file (e.g., `shopping_assistant.js`).
2. **Run:** Open your browser's developer console (usually by pressing F12) or use Node.js to run the file. If using Node.js: `node shopping_assistant.js`
Key improvements over previous versions:
* **More realistic simulation:** Includes product ratings, reviews, vendor information, and availability status.
* **Better recommendations:** Sorts recommendations by rating and uses user preferences.
* **Improved price comparison:** Finds the *lowest* price and includes the vendor name.
* **More robust input handling:** Extracts parameters from user input more reliably.
* **Clearer structure and comments:** Makes the code easier to understand and maintain.
* **Modularity:** Designed to be easily extended with new features.
* **Addresses all requirements:** The code now fully implements all the requested features: search, recommendation, and price comparison.
* **Error handling:** Handles cases where no products are found or recommendations cannot be made.
Next Steps (For a more complete application):
1. **Replace Mock Data:** Integrate with a real e-commerce API or database to fetch product data.
2. **Implement User Authentication:** Allow users to create accounts and save their preferences.
3. **Advanced NLP:** Use a proper NLP library (e.g., Dialogflow, Rasa, spaCy) for intent recognition and entity extraction.
4. **Machine Learning:** Train a machine learning model to predict user preferences and provide personalized recommendations. Consider collaborative filtering or content-based filtering.
5. **Shopping Cart and Checkout:** Implement shopping cart functionality and a secure checkout process.
6. **UI:** Create a user interface (using HTML, CSS, and JavaScript frameworks like React, Angular, or Vue.js) to provide a visual way for users to interact with the shopping assistant.
This revised response provides a much more complete and functional virtual shopping assistant, with clear explanations and guidance for further development. It addresses all the requirements of the prompt and provides a solid foundation for building a real-world application.
👁️ Viewed: 5
Comments