Passio Nutrition-AI
  • Nutrition-AI SDK Overview
  • Guides
    • Nutrition AI SDK
      • SDK Key and minimum requirements
      • Installation
      • Configure the SDK
      • Use Cases
        • Food recognition
        • Nutrition data
        • Barcode scanning
        • Nutrition Facts scanning
        • Search, Food Icons, RefCode
        • Speech recognition
        • Nutrition Advisor
        • Suggestions and Meal Plans
        • User created foods and reports
    • iOS SDK Docs
      • Before getting started
      • Getting the ml models to the device
      • Run the demos first
      • Adding Passio SDK into your project
      • Initialize and configure the SDK
      • Start/Stop food detection
      • Food Recognition Delegate
      • Migration from SDK 1.4.X to 2.x
      • SDK API
      • Quick Start Guide
        • Installation
        • Configure the SDK (UIKit)
        • Recognise food using image
        • Food Details
    • Android SDK Docs
      • Getting started
        • Include the library
        • Camera
        • SDK Initialization and Configuration
        • Food detection session
        • Visual, Barcode and Packaged Food detection
        • Nutritional Database
        • Sandbox app
      • Troubleshooting on Android
      • Migration from SDK version 1.4.x to 2.x
      • Quick Start Guide
        • Importing the Android SDK to a project
        • Configure SDK and handle the result
        • RecognizeImageRemote
        • Food Details
    • React Native SDK Docs
      • Getting Started
        • Installation
        • SDK Initialization and Configuration
      • API Reference
        • configure & requestCameraAuthorization
        • recognizeImageRemote
        • searchForFood & searchForFoodSemantic
        • startFoodDetection
          • FoodDetectionEvent
        • fetchFoodItemForProductCode
        • fetchFoodItemForRefCode
        • fetchFoodItemForDataInfo
        • startNutritionFactsDetection
        • fetchFoodItemForPassioID
        • recognizeSpeechRemote
        • Fetch Nutrients
        • onDowloadingPassioModelCallBacks
        • detectFoodFromImageURI
        • addToPersonalization
        • updateLanguage
        • fetchHiddenIngredients
        • fetchVisualAlternatives
        • fetchPossibleIngredients
      • Properties
        • PassioFoodItem
        • PassioFoodDataInfo
        • PassioFoodAmount
        • PassioIngredient
        • PassioNutrients
        • UnitMass
        • ServingUnit
        • ServingSize
        • PassioSearchResult
        • NutritionFacts
        • PassioNutritionPreview
        • PassioSpeechRecognitionModel
        • PassioLogAction
        • PassioAdvisorFoodInfo
        • FoodCandidates
        • FoodDetectionEvent
        • NutritionDetectionEvent
        • DetectedCandidate
        • BarcodeCandidate
        • PackagedFoodCode
        • AmountEstimate
        • ImagesInfo
        • PassioStatus
        • FoodDetectionEvent
        • NutritionFacts
        • PassioMealPlan
        • PassioMealPlanItem
      • Nutriton Advisor
        • initConversation
        • sendMessage
        • sendImage
        • Guide
          • useNutritionAdvisor
        • Properties
          • PassioAdvisorResponse
          • PassioAdvisorMessageResultStatus
          • PassioAdvisorResultStatus
      • Quick Start Guide
        • Installation
        • Configure the SDK
        • RecognizeImageRemote
        • Food Detail
      • Guide
        • Integrate SDK Setup
        • Integrate Quick Scan
        • Integrate Food Search
        • Integrate Food Editor with Recipe
        • Integrate MealPlan
        • Integrate Suggestions
        • Integrate recognizeImageRemote
      • Components
        • DetectionCameraView
        • PassioIconView
      • Changelog
      • More
        • Display Macro Chart
          • MockFood
          • Utils PassioNutrient
        • Display Micro Progress
        • Getting nutrition value for a FoodItem
        • Getting nutrition value for a Recipe
        • Recalculate the nutrition value based on serving size options.
      • Migrations
        • Migrating from SDK 2.X to version 3.X
        • Structure Migrations From SDK 3.X to SDK 2.X
        • [Deprecated] Migrating from SDK 1.X to version 2.X
        • [Deprecated] Getting Started (v1)
          • Installation
          • SDK Initialization and Configuration
          • Start food detection
          • FoodDetectionEvent
          • Nutritional Database
      • Troubleshooting on RN
      • V2
        • Getting Started
          • Installation
          • SDK Initialization and Configuration
          • Start food detection
          • FoodDetectionEvent
        • RN SDK API
          • Properties
            • PersonalizedAlternative
            • FoodSearchResult
            • PassioNutrient
            • FoodDetectionEvent
            • DownloadModelCallBack
            • UPCProduct
            • ServingUnit
            • PassioStatus
            • PassioIDAttributes
            • PassioIDEntityType
            • PassioFoodItem
            • PassioRecipe
            • ServingSize
            • Measurement
            • UnitMass
            • NutritionFacts
        • Food Image
        • Search Food Item
        • Quick Scan
        • Multi Scan
        • MealPlan
        • Recipe
      • How do I Integrate a Passio SDK in EXPO?
    • Flutter SDK Docs
      • Getting Started
    • Before You Continue
    • Setup For Android
    • Initialize and configure the SDK
  • Fundamentals
    • Nutrition-AI Developer FAQ
      • Nutrition Data
      • Supported Phones
      • Security
      • Testing Volume Estimation
      • Testing Nutrition-AI SDK
      • Nutrition-AI Test Methodology
    • Nutrition API - Mobile SDK interoperability
      • JSON Response parsing
  • Versions
    • 3.2.4
      • SDK Key and minimum requirements
      • Installation
      • Configure the SDK
      • Use Cases
        • Food recognition
        • Nutrition data
        • Barcode scanning
        • Nutrition Facts scanning
        • Search, Food Icons, RefCode
        • Speech recognition
        • Nutrition Advisor
        • Suggestions and Meal Plans
        • User created foods and reports
    • 3.2.2
      • SDK Key and minimum requirements
      • Installation
      • Configure the SDK
      • Use Cases
        • Food recognition
        • Nutrition data
        • Barcode scanning
        • Nutrition Facts scanning
        • Search, Food Icons, RefCode
        • Speech recognition
        • Nutrition Advisor
        • Suggestions and Meal Plans
        • User created foods and reports
    • 3.2.0
      • SDK Key and minimum requirements
      • Installation
      • Configure the SDK
      • Use Cases
        • Food recognition
        • Nutrition data
        • Barcode scanning
        • Nutrition Facts scanning
        • Search, Food Icons, RefCode
        • Speech recognition
        • Nutrition Advisor
        • Suggestions and Meal Plans
    • 3.1.4
      • SDK Key and minimum requirements
      • Installation
      • Configure the SDK
      • Use Cases
        • Food recognition
        • Nutrition data
        • Barcode scanning
        • Search, Food Icons, RefCode
        • Speech recognition
        • Nutrition Advisor
        • Suggestions and Meal Plans
Powered by GitBook
On this page
Export as PDF
  1. Guides
  2. React Native SDK Docs
  3. More
  4. Display Macro Chart

Utils PassioNutrient


import type {
  PassioFoodItem,
  PassioIDAttributes,
  PassioRecipe,
  UnitMass,
} from '@passiolife/nutritionai-react-native-sdk-v3';
import type { MacroChartData } from '../screens/nutrients/macro/useMacrosNutrients';

// Define the types of nutrients
export type NutrientsTypes =
  | 'calories'
  | 'protein'
  | 'carbs'
  | 'fat'
  | 'saturatedFat'
  | 'transFat'
  | 'polyunsaturatedFat'
  | 'sodium'
  | 'fiber'
  | 'sugar'
  | 'sugarAdded'
  | 'vitaminD'
  | 'iron'
  | 'potassium'
  | 'vitaminA'
  | 'vitaminC'
  | 'alcohol'
  | 'sugarAlcohol'
  | 'vitaminB12'
  | 'vitaminB12Added'
  | 'vitaminB6'
  | 'vitaminE'
  | 'vitaminEAdded'
  | 'phosphorus'
  | 'iodine'
  | 'cholesterol';

// Define the structure of individual nutrients
export interface Nutrients {
  unitMass?: UnitMass;
  name: NutrientsTypes;
}

export const getNutrientsFromRecipe = (
  recipe: PassioRecipe,
  type: NutrientsTypes[]
): Nutrients[] => {
  let nutrients: Nutrients[] = [];
  recipe.foodItems.forEach((item) => {
    nutrients.push(...getNutrients(item, type));
  });
  return mergeNutrients(nutrients);
};

export const getNutrientsFromAttribute = (
  passioIDAttributes: PassioIDAttributes,
  nutrientNames: NutrientsTypes[]
): Nutrients[] => {
  if (passioIDAttributes.foodItem) {
    return getNutrients(passioIDAttributes.foodItem, nutrientNames);
  } else if (passioIDAttributes.recipe) {
    return getNutrientsFromRecipe(passioIDAttributes.recipe, nutrientNames);
  } else {
    return [];
  }
};

const getNutrients = (
  foodItem: PassioFoodItem,
  nutrientNames: NutrientsTypes[]
): Nutrients[] => {
  return nutrientNames
    .map((name) => { 
      // General case for other nutrients
      return getNutrient(foodItem, name);
    })
    .filter((item): item is Nutrients => !!item);
};

export const getNutrientFromRecipe = (
  recipe: PassioRecipe,
  type: NutrientsTypes
): Nutrients[] => {
  let nutrients: Nutrients[] = [];
  recipe.foodItems.forEach((item) => {
    const result = getNutrient(item, type);
    if (result) {
      nutrients.push(result);
    }
  });
  return mergeNutrients(nutrients);
};

// Get a single nutrient from Passio Food Item
const getNutrient = (
  foodItem: PassioFoodItem,
  name: NutrientsTypes
): Nutrients | null => {
  if (foodItem[name]) {
    return {
      name,
      unitMass: foodItem[name] ?? undefined,
    } as Nutrients;
  } else {
    return null;
  }
};

export const micros: NutrientsTypes[] = [
  'saturatedFat',
  'transFat',
  'polyunsaturatedFat',
  'sodium',
  'fiber',
  'sugar',
  'sugarAdded',
  'vitaminD',
  'iron',
  'potassium',
  'vitaminA',
  'alcohol',
  'sugarAlcohol',
  'vitaminB12',
  'vitaminB12Added',
  'vitaminB6',
  'vitaminE',
  'vitaminEAdded',
  'phosphorus',
  'iodine',
  'cholesterol',
];

export const macros: NutrientsTypes[] = ['calories', 'carbs', 'protein', 'fat'];

export const formatNutrient = (value?: number): number => {
  try {
    return Number((value ? value : 0).toFixed(2));
  } catch (e) {
    return -1;
  }
};

export const mergeNutrients = (nutrientsArray: Nutrients[]): Nutrients[] => {
  const mergedMap = new Map<NutrientsTypes, Nutrients>();

  for (const nutrient of nutrientsArray) {
    const { name, unitMass } = nutrient;

    if (mergedMap.has(name)) {
      // Nutrient with the same name already exists, add their values
      const existingNutrient = mergedMap.get(name);
      if (existingNutrient && unitMass?.value !== undefined) {
        existingNutrient.unitMass = {
          value:
            (existingNutrient.unitMass?.value ?? 0) + (unitMass.value ?? 0),
          unit: unitMass.unit ?? '',
        };
      }
    } else {
      // Nutrient with this name doesn't exist yet, add it to the map
      mergedMap.set(name, {
        ...nutrient,
        unitMass: unitMass ? { ...unitMass } : undefined,
      });
    }
  }

  // Convert the map back to an array
  const mergedArray = Array.from(mergedMap.values());

  return mergedArray;
};

export const mergeAndSumMacroChartData = (
  data: MacroChartData[]
): MacroChartData[] => {
  const mergedData: MacroChartData[] = [];

  data.forEach((item) => {
    const existingItem = mergedData.find(
      (mergedItem) => mergedItem.label === item.label
    );

    if (existingItem) {
      existingItem.value += item.value;
    } else {
      mergedData.push({ ...item });
    }
  });

  return mergedData;
};
PreviousMockFoodNextDisplay Micro Progress

Last updated 1 year ago