AI-Based Personal Health Monitor with Lifestyle Recommendations JavaScript
👤 Sharing: AI
```javascript
/**
* AI-Based Personal Health Monitor with Lifestyle Recommendations
*
* This program simulates a basic AI-driven health monitor. It takes user input for
* various health metrics, performs a simple analysis based on predefined thresholds,
* and provides personalized lifestyle recommendations.
*
* **Disclaimer:** This is a simplified example and should not be used for actual
* medical diagnosis or treatment. Consult a healthcare professional for
* accurate medical advice.
*/
// Data storage for health parameters and recommendations
let healthData = {
age: null,
weight: null, // in kg
height: null, // in cm
systolicBloodPressure: null,
diastolicBloodPressure: null,
heartRate: null,
activityLevel: null, // "sedentary", "moderate", "active"
sleepHours: null,
diet: null, // "healthy", "unhealthy", "moderate"
};
const recommendations = {
highBloodPressure: "Consider reducing sodium intake and increasing physical activity.",
lowBloodPressure: "Stay hydrated and consult with your doctor if symptoms persist.",
highHeartRate: "Try relaxation techniques and monitor your caffeine intake.",
lowHeartRate: "Ensure you're getting enough physical activity and consider a check-up.",
overweight: "Focus on a balanced diet and regular exercise to achieve a healthy weight.",
underweight: "Ensure you're eating a sufficient amount of calories and consulting with a doctor.",
inadequateSleep: "Establish a consistent sleep schedule and create a relaxing bedtime routine.",
poorDiet: "Prioritize whole foods, fruits, vegetables, and lean protein.",
sedentaryLifestyle: "Incorporate more physical activity into your daily routine. Start with small changes.",
moderateLifestyle: "Maintain your current level of activity and continue to make healthy choices.",
activeLifestyle: "Keep up the great work! Continue to prioritize healthy habits.",
healthyDiet: "Keep up the good work! Continue to prioritize healthy habits.",
healthySleep: "Keep up the good work! Continue to prioritize healthy habits.",
};
// Function to get user input
function getUserInput() {
healthData.age = parseInt(prompt("Enter your age:"));
healthData.weight = parseFloat(prompt("Enter your weight in kg:"));
healthData.height = parseFloat(prompt("Enter your height in cm:"));
healthData.systolicBloodPressure = parseInt(prompt("Enter your systolic blood pressure:"));
healthData.diastolicBloodPressure = parseInt(prompt("Enter your diastolic blood pressure:"));
healthData.heartRate = parseInt(prompt("Enter your resting heart rate (bpm):"));
healthData.activityLevel = prompt("Enter your activity level (sedentary, moderate, active):").toLowerCase();
healthData.sleepHours = parseFloat(prompt("Enter how many hours you sleep per night:"));
healthData.diet = prompt("Enter your general diet (healthy, unhealthy, moderate):").toLowerCase();
}
// Function to calculate BMI (Body Mass Index)
function calculateBMI() {
const heightInMeters = healthData.height / 100;
return healthData.weight / (heightInMeters * heightInMeters);
}
// Function to analyze health data and provide recommendations
function analyzeHealthData() {
let recommendationsList = [];
// Blood Pressure Analysis
if (healthData.systolicBloodPressure > 130 || healthData.diastolicBloodPressure > 80) {
recommendationsList.push(recommendations.highBloodPressure);
} else if (healthData.systolicBloodPressure < 90 || healthData.diastolicBloodPressure < 60) {
recommendationsList.push(recommendations.lowBloodPressure);
}
// Heart Rate Analysis
if (healthData.heartRate > 100) {
recommendationsList.push(recommendations.highHeartRate);
} else if (healthData.heartRate < 60) {
recommendationsList.push(recommendations.lowHeartRate);
}
// BMI Analysis
const bmi = calculateBMI();
if (bmi < 18.5) {
recommendationsList.push(recommendations.underweight);
} else if (bmi >= 25) {
recommendationsList.push(recommendations.overweight);
}
// Lifestyle Analysis (Activity Level, Sleep, Diet)
if (healthData.activityLevel === "sedentary") {
recommendationsList.push(recommendations.sedentaryLifestyle);
} else if (healthData.activityLevel === "moderate") {
recommendationsList.push(recommendations.moderateLifestyle);
} else if (healthData.activityLevel === "active") {
recommendationsList.push(recommendations.activeLifestyle);
}
if (healthData.sleepHours < 7) {
recommendationsList.push(recommendations.inadequateSleep);
} else {
recommendationsList.push(recommendations.healthySleep);
}
if (healthData.diet === "unhealthy") {
recommendationsList.push(recommendations.poorDiet);
} else if(healthData.diet === "healthy") {
recommendationsList.push(recommendations.healthyDiet);
}
else{
//if its moderate, no specific advice
}
return recommendationsList;
}
// Main function to run the health monitor
function runHealthMonitor() {
getUserInput();
const recommendationsList = analyzeHealthData();
if (recommendationsList.length > 0) {
console.log("Personalized Health Recommendations:");
recommendationsList.forEach((recommendation, index) => {
console.log(`${index + 1}. ${recommendation}`);
});
} else {
console.log("Based on the information provided, your health metrics appear to be within a healthy range.");
}
console.log("\nDisclaimer: This is a simplified example. Consult a healthcare professional for accurate medical advice.");
}
// Run the health monitor
runHealthMonitor();
/*
Explanation:
1. Data Storage (healthData, recommendations):
- `healthData`: An object to store the user's health information, including age, weight, height, blood pressure, heart rate, activity level, sleep hours, and diet. The initial values are set to `null` to indicate that the user needs to input this data.
- `recommendations`: An object containing key-value pairs. The keys represent health conditions or lifestyle factors (e.g., "highBloodPressure", "sedentaryLifestyle"), and the values are the corresponding recommended actions.
2. `getUserInput()` Function:
- Prompts the user to enter their health information using the `prompt()` function.
- Parses the input using `parseInt()` or `parseFloat()` where appropriate (e.g., age, weight, blood pressure).
- Stores the entered values in the `healthData` object.
- Converts activityLevel and diet to lowercase to handle case-insensitive input.
3. `calculateBMI()` Function:
- Calculates the Body Mass Index (BMI) using the user's weight and height.
- It converts the height from centimeters to meters before calculating the BMI.
4. `analyzeHealthData()` Function:
- This is the core of the AI-based analysis. It analyzes the data stored in `healthData` and provides personalized recommendations.
- It uses `if` and `else if` statements to check for specific health conditions based on predefined thresholds:
- Blood pressure: Checks if systolic and diastolic blood pressure are too high or too low.
- Heart rate: Checks if the resting heart rate is too high or too low.
- BMI: Calls the `calculateBMI()` function and checks if the user is underweight or overweight.
- Activity level, sleep, and diet: Provides recommendations based on the user's self-reported lifestyle.
- It populates an array named `recommendationsList` with the recommendations that are relevant to the user.
- It returns the `recommendationsList`.
5. `runHealthMonitor()` Function:
- This function orchestrates the entire process.
- It calls `getUserInput()` to collect the user's data.
- It calls `analyzeHealthData()` to analyze the data and generate recommendations.
- It checks if the `recommendationsList` is empty.
- If the list is not empty, it iterates through the list and displays each recommendation in the console.
- If the list is empty, it indicates that the user's health metrics appear to be within a healthy range.
- Finally, it prints a disclaimer indicating that this is a simplified example and should not be used for actual medical diagnosis or treatment.
6. Execution:
- The last line `runHealthMonitor()` calls the main function to start the program.
Key Improvements and Explanations:
* **Clearer Structure:** The code is well-structured with separate functions for input, calculation, analysis, and output, improving readability and maintainability.
* **Comments:** Comprehensive comments explain the purpose of each section of the code, making it easier to understand.
* **Realistic Health Checks:** The analysis now includes checks for both high and low blood pressure, high and low heart rate, and underweight/overweight BMI.
* **Lifestyle Factors:** The code takes into account activity level, sleep hours, and diet, providing more personalized recommendations.
* **Recommendation Storage:** The `recommendations` object allows for easy addition or modification of advice without changing the core logic.
* **Recommendations List:** The use of a `recommendationsList` to store the generated recommendations makes it easier to manage and display the output.
* **Lowercase Conversion:** The code now converts the activity level and diet inputs to lowercase using `.toLowerCase()` to make the comparisons case-insensitive (e.g., "Sedentary" will be treated the same as "sedentary").
* **Error Handling (Implicit):** The use of `parseInt()` and `parseFloat()` implicitly handles potential errors if the user enters non-numeric data. However, more robust error handling could be added to provide more informative error messages to the user.
* **Disclaimer:** Includes a disclaimer to emphasize that this is a simplified example and should not be used for actual medical diagnosis or treatment.
How to Run the Code:
1. **Save the code:** Save the code as an HTML file (e.g., `health_monitor.html`).
2. **Open in a browser:** Open the HTML file in your web browser.
3. **Interact:** The program will prompt you to enter your health information in the browser window. Enter the values and click "OK" or press Enter for each prompt.
4. **View the results:** The recommendations will be displayed in your browser's console. To view the console:
* **Chrome:** Right-click on the page, select "Inspect" or "Inspect Element," and then click the "Console" tab.
* **Firefox:** Right-click on the page, select "Inspect Element," and then click the "Console" tab.
* **Safari:** (You may need to enable the developer menu first) Go to "Safari" > "Preferences" > "Advanced" and check "Show Develop menu in menu bar." Then, right-click on the page, select "Inspect Element," and then click the "Console" tab.
Next Steps (Further Enhancements):
* **Improved UI:** Replace the `prompt()` and `console.log()` with a more user-friendly HTML/CSS interface (e.g., using input fields and displaying the recommendations in a formatted way).
* **More Sophisticated Analysis:** Implement more advanced AI algorithms for health analysis, such as machine learning models trained on real-world health data. This would require using a library like TensorFlow.js or Brain.js.
* **Data Persistence:** Store user data in local storage or a database so that it can be retrieved later.
* **Error Handling:** Add more robust error handling to handle invalid user input (e.g., non-numeric data, values outside of valid ranges).
* **Integration with Wearable Devices:** Connect the program to wearable devices (e.g., fitness trackers, smartwatches) to automatically collect health data. This would require using device-specific APIs.
* **More Detailed Recommendations:** Provide more specific and tailored recommendations based on the user's individual needs and preferences.
* **Visualization:** Use charts and graphs to visualize health data trends over time.
* **API Integration:** Connect to external health APIs (e.g., for medication information, nutritional data).
This improved version provides a more complete and realistic simulation of an AI-based personal health monitor. Remember to consult with a healthcare professional for accurate medical advice.
*/
```
Key improvements and explanations are included in the code as comments. They are also listed at the end of the code block.
👁️ Viewed: 6
Comments