AI-Powered Personal Health Monitor with Lifestyle Recommendations JavaScript

👤 Sharing: AI
```javascript
// AI-Powered Personal Health Monitor with Lifestyle Recommendations

/**
 * This JavaScript program simulates a basic AI-powered personal health monitor.
 * It takes user input (simulated here) related to health metrics and lifestyle factors.
 * Based on these inputs, it provides personalized health insights and lifestyle recommendations.
 *
 * **Note:** This is a simplified example and does not replace professional medical advice.  A real-world
 * application would require significantly more sophisticated AI models, data analysis, and integration with
 * actual health monitoring devices.
 */

// --- Data Structures and Constants ---

const healthData = {
  age: 30,
  weight: 75, // kg
  height: 175, // cm
  activityLevel: 'moderate', // 'sedentary', 'light', 'moderate', 'active', 'very active'
  sleepHours: 7,
  stressLevel: 'medium', // 'low', 'medium', 'high'
  bloodPressureSystolic: 120, // mmHg (millimeter of mercury)
  bloodPressureDiastolic: 80, // mmHg
  heartRate: 70, // bpm (beats per minute)
};

const activityLevelMultipliers = {
  sedentary: 1.2,
  light: 1.375,
  moderate: 1.55,
  active: 1.725,
  very_active: 1.9, // Corrected key to match snake_case for consistency.  Consider consistent casing throughout.
};

const idealBloodPressure = {
    systolic: 120,
    diastolic: 80
};

const idealHeartRate = {
    min: 60,
    max: 100
};

// --- Helper Functions ---

/**
 * Calculates Body Mass Index (BMI).
 * @param {number} weight - Weight in kilograms.
 * @param {number} height - Height in centimeters.
 * @returns {number} BMI value.
 */
function calculateBMI(weight, height) {
  const heightInMeters = height / 100;
  return weight / (heightInMeters * heightInMeters);
}

/**
 * Interprets BMI value and returns a category.
 * @param {number} bmi - BMI value.
 * @returns {string} BMI category.
 */
function interpretBMI(bmi) {
  if (bmi < 18.5) {
    return 'Underweight';
  } else if (bmi < 25) {
    return 'Normal weight';
  } else if (bmi < 30) {
    return 'Overweight';
  } else {
    return 'Obese';
  }
}

/**
 * Calculates Basal Metabolic Rate (BMR) using the Mifflin-St Jeor equation (for men).
 * @param {number} weight - Weight in kilograms.
 * @param {number} height - Height in centimeters.
 * @param {number} age - Age in years.
 * @returns {number} BMR value.
 */
function calculateBMR(weight, height, age) {
  // Mifflin-St Jeor equation for men: (10 x weight in kg) + (6.25 x height in cm) - (5 x age in years) + 5
  return (10 * weight) + (6.25 * height) - (5 * age) + 5;
}

/**
 * Estimates daily calorie needs based on BMR and activity level.
 * @param {number} bmr - Basal Metabolic Rate.
 * @param {string} activityLevel - Activity level ('sedentary', 'light', 'moderate', 'active', 'very_active').
 * @returns {number} Estimated daily calorie needs.
 */
function estimateDailyCalories(bmr, activityLevel) {
  const multiplier = activityLevelMultipliers[activityLevel];
  if (!multiplier) {
    console.warn(`Invalid activity level: ${activityLevel}. Using moderate activity as default.`);
    return bmr * activityLevelMultipliers.moderate;
  }
  return bmr * multiplier;
}

/**
 * Provides stress management recommendations based on stress level.
 * @param {string} stressLevel - Stress level ('low', 'medium', 'high').
 * @returns {string} Stress management recommendations.
 */
function getStressManagementRecommendations(stressLevel) {
  switch (stressLevel) {
    case 'low':
      return "Continue practicing healthy habits to maintain low stress levels.";
    case 'medium':
      return "Consider incorporating relaxation techniques like meditation or yoga into your routine.";
    case 'high':
      return "Prioritize stress reduction activities. Seek professional help if needed.";
    default:
      return "Invalid stress level. Please provide a valid stress level ('low', 'medium', 'high').";
  }
}

/**
 * Provides sleep hygiene recommendations based on sleep hours.
 * @param {number} sleepHours - Number of sleep hours.
 * @returns {string} Sleep hygiene recommendations.
 */
function getSleepHygieneRecommendations(sleepHours) {
  if (sleepHours < 7) {
    return "Aim for 7-9 hours of sleep per night. Establish a consistent sleep schedule and create a relaxing bedtime routine.";
  } else if (sleepHours > 9) {
    return "While you're getting sufficient sleep, ensure the quality of your sleep is good.  Avoid excessive daytime napping if you're still feeling fatigued.";
  } else {
    return "You're getting an adequate amount of sleep. Maintain your healthy sleep habits.";
  }
}


/**
 * Provides blood pressure recommendations based on systolic and diastolic values.
 * @param {number} systolic - Systolic blood pressure.
 * @param {number} diastolic - Diastolic blood pressure.
 * @returns {string} Blood pressure recommendations.
 */
function getBloodPressureRecommendations(systolic, diastolic) {
    if (systolic < 90 || diastolic < 60) {
        return "Your blood pressure is low. Consult with a healthcare professional.";
    } else if (systolic > 129 || diastolic > 89) {
        return "Your blood pressure is high. Lifestyle changes and/or medication may be necessary. Consult with a healthcare professional.";
    } else if (systolic > 120 || diastolic > 80) {
        return "Your blood pressure is elevated. Focus on lifestyle changes like diet and exercise.";
    } else {
        return "Your blood pressure is within the normal range.";
    }
}

/**
 * Provides heart rate recommendations based on beats per minute.
 * @param {number} heartRate - Heart rate (beats per minute).
 * @returns {string} Heart rate recommendations.
 */
function getHeartRateRecommendations(heartRate) {
    if (heartRate < idealHeartRate.min) {
        return "Your heart rate is lower than normal.  Discuss with your doctor if you experience dizziness or fatigue.";
    } else if (heartRate > idealHeartRate.max) {
        return "Your heart rate is higher than normal.  Monitor your heart rate and consult a doctor if it persists.";
    } else {
        return "Your heart rate is within the normal range.";
    }
}



// --- Main Function ---

function main() {
  console.log('--- Personal Health Monitor ---');

  // 1. Calculate BMI and provide interpretation
  const bmi = calculateBMI(healthData.weight, healthData.height);
  const bmiCategory = interpretBMI(bmi);
  console.log(`BMI: ${bmi.toFixed(2)} (${bmiCategory})`);

  // 2. Estimate Daily Calorie Needs
  const bmr = calculateBMR(healthData.weight, healthData.height, healthData.age);
  const dailyCalories = estimateDailyCalories(bmr, healthData.activityLevel);
  console.log(`Estimated Daily Calorie Needs: ${dailyCalories.toFixed(0)} calories`);

  // 3. Provide Stress Management Recommendations
  const stressRecommendations = getStressManagementRecommendations(healthData.stressLevel);
  console.log(`Stress Management Recommendations: ${stressRecommendations}`);

  // 4. Provide Sleep Hygiene Recommendations
  const sleepRecommendations = getSleepHygieneRecommendations(healthData.sleepHours);
  console.log(`Sleep Recommendations: ${sleepRecommendations}`);

  // 5. Provide Blood Pressure Recommendations
  const bloodPressureRecommendations = getBloodPressureRecommendations(healthData.bloodPressureSystolic, healthData.bloodPressureDiastolic);
  console.log(`Blood Pressure Recommendations: ${bloodPressureRecommendations}`);

    // 6. Provide Heart Rate Recommendations
  const heartRateRecommendations = getHeartRateRecommendations(healthData.heartRate);
  console.log(`Heart Rate Recommendations: ${heartRateRecommendations}`);

  console.log('--- End of Report ---');
}

// --- Run the Program ---
main();
```

Key improvements and explanations:

* **Clearer Structure and Comments:**  The code is now organized with meaningful comments explaining each section and function.  This makes it much easier to understand the program's flow and purpose.
* **Data Structures for Clarity:**  `healthData`, `activityLevelMultipliers`, `idealBloodPressure`, and `idealHeartRate` are defined as objects. This improves readability and makes it easier to modify or extend the program with more health metrics.
* **BMI Calculation and Interpretation:** Implements `calculateBMI` and `interpretBMI` functions, providing a valuable health indicator.
* **BMR and Calorie Estimation:** Calculates Basal Metabolic Rate (BMR) and estimates daily calorie needs based on activity level.  Uses the more accurate Mifflin-St Jeor equation for BMR calculation.
* **Activity Level Handling:**  Handles different activity levels with a multiplier lookup. Includes input validation and a default value if the activity level is invalid.  Added a corrected the key `very_active` to snake_case to be consistent.  Consider standardizing casing conventions throughout the program.
* **Stress Management and Sleep Hygiene Recommendations:**  Provides personalized recommendations based on stress levels and sleep hours.
* **Blood Pressure Recommendations:** Added logic to interpret blood pressure readings and provide tailored recommendations.  Incorporates multiple blood pressure categories (low, elevated, high).
* **Heart Rate Recommendations:** Added logic to interpret heart rate readings and provide recommendations.
* **Error Handling/Input Validation:** Includes basic input validation in the `estimateDailyCalories` function to handle invalid activity levels.  The stress and sleep functions could benefit from additional validation.
* **Modularity:** Functions like `calculateBMI`, `getStressManagementRecommendations`, and `getSleepHygieneRecommendations` make the code more modular and reusable.
* **Readability:** Used descriptive variable names and consistent formatting to improve readability.
* **More Realistic Recommendations:** Recommendations are more tailored and actionable.
* **Disclaimer:** Added a crucial disclaimer at the beginning to emphasize that this is a simulation and does not replace professional medical advice.  **THIS IS VERY IMPORTANT.**
* **Comprehensive Output:** The `main` function now presents a complete health report with various metrics and recommendations.
* **Up-to-date Recommendations:**  Blood pressure recommendations are updated based on current guidelines.

How to run the code:

1.  **Save:** Save the code as a `.js` file (e.g., `health_monitor.js`).
2.  **Run:** Open your browser's developer console (usually by pressing F12) or use Node.js from your terminal by typing `node health_monitor.js`.

This improved version provides a much more comprehensive and realistic simulation of an AI-powered personal health monitor. Remember to expand on this foundation to create a truly useful application.
👁️ Viewed: 4

Comments