-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.js
92 lines (80 loc) · 2.29 KB
/
model.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
module.exports = class {
constructor() {
this.foods = [];
this.fallbackNutrient = {
amount: 0,
unitName: null
};
}
addFood(food) {
this.foods.push(food);
}
addData(data) {
data.forEach(this.addFood, this);
}
getResultsFromSearch(searchPattern, start, limit) {
const searchRegExp = new RegExp(searchPattern, "gi");
return this.foods
.filter(food => searchRegExp.test(food.description))
.slice(start, start + limit)
.map(this.reduceProperties, this);
}
reduceProperties(food) {
const { fdcId, description, portions, nutrients } = food;
const portion = portions[0];
const [calories, protein, carbohydrate, fat] = this.calculateMacroNutrients(
nutrients,
portion
);
return {
fdcId,
description,
portion,
calories,
protein,
carbohydrate,
fat
};
}
calculateMacroNutrients(nutrients, portion) {
const { gramWeight } = portion;
return this.getMacroNutrientsFrom(nutrients).map(macronutrient =>
this.calculateAmount(macronutrient, gramWeight)
);
}
getMacroNutrientsFrom(nutrients) {
const calories = this.findNutrientBy("unitName", "kcal", nutrients);
const protein = this.findNutrientBy("name", "Protein", nutrients);
const carbohydrate = this.findNutrientBy("name", "Carbohydrate", nutrients);
const fat = this.findNutrientBy("name", "Total lipid", nutrients);
return [calories, protein, carbohydrate, fat];
}
findNutrientBy(key, value, nutrients) {
const regularExpression = new RegExp(value, "gi");
return (
nutrients.find(nutrient => regularExpression.test(nutrient[key])) ||
this.fallbackNutrient
);
}
calculateAmount(nutrient, gramWeight) {
const { name, amount, unitName } = nutrient;
const calculatedAmount = (amount / 100) * gramWeight;
return {
name,
amount: calculatedAmount,
unitName
};
}
getFoodById(fdcId) {
const food = this.foods.find(food => food.fdcId === fdcId);
this.removeKiloJoulesNutrient(food);
return food;
}
removeKiloJoulesNutrient(food) {
const { kiloJoulesNutrient } = this;
food.nutrients = food.nutrients.filter(kiloJoulesNutrient);
}
kiloJoulesNutrient(nutrient) {
return nutrient.unitName !== "kj";
}
};