-
Notifications
You must be signed in to change notification settings - Fork 1
/
meal_calculator.js
97 lines (87 loc) · 2.11 KB
/
meal_calculator.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
93
94
95
96
var mealCalculator = {
setMenu: function(menu){
this.menu = menu;
this.orderedMeals = null;
},
getOrderedMeals: function(){
if(!this.orderedMeals){ // call on demand
var orderedMeals = [];
for(var m in this.menu.meals){
orderedMeals.push(m);
}
var m = this;
this.orderedMeals = orderedMeals.sort(function(a,b){
return m.getMoneySavedByMeal.call(m, b) - m.getMoneySavedByMeal.call(m, a);
});
}
return this.orderedMeals;
},
calculate: function(input){
var foods = this.getValidFoods(input),
meal = this.getWorthiestMeal(foods),
result = [];
while(meal != null){
result.push(meal);
foods = this.subtractMealFoodFromItems(foods, meal);
meal = this.getWorthiestMeal(foods);
}
return $.merge(result,foods);
},
getValidFoods: function(val){
if(!val) return [];
if(!$.isArray(val)) val = val.split(",")
var m = this;
var inputItems = $.map(val, function(n){
return $.trim(n);
});
var outputItems = $.grep(inputItems, function(n){
return m.menu.foods[$.trim(n)] != null;
});
return outputItems;
},
getWorthiestMeal: function(items){
for(var i=0; i<this.getOrderedMeals().length; i++){
var meal = this.getOrderedMeals()[i];
if(this.matchMealFood(items, meal)){
return meal;
}
}
return null;
},
matchMealFood: function(items, meal){
var foods = this.menu.meals[meal].foods;
for(var f in foods){
var index = $.inArray(foods[f], items);
if(index == -1){
return false;
}
else{
items = $.grep(items, function(n,i){
return i!=index;
});
}
}
return true;
},
getMoneySavedByMeal: function(meal){
var meal = this.menu.meals[meal];
if(!meal)
return 0;
var foods = this.menu.foods;
var individualTotal = 0;
$.each(meal.foods, function(i, n){
individualTotal += foods[n].price;
});
return individualTotal - meal.price;
},
subtractMealFoodFromItems: function(items, meal){
var foods = this.menu.meals[meal].foods;
for(var f in foods){
var index = $.inArray(foods[f], items);
items = $.grep(items, function(n,i){
return i!=index;
});
}
return items;
}
}