Transaction.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. class TransactionRecipe{
  2. constructor(recipe, quantity, merchant){
  3. this._recipe = merchant.getRecipe(recipe);
  4. this._quantity = quantity;
  5. }
  6. get recipe(){
  7. return this._recipe;
  8. }
  9. get quantity(){
  10. return this._quantity;
  11. }
  12. }
  13. class Transaction{
  14. constructor(id, date, recipes, parent){
  15. this._id = id;
  16. this._date = new Date(date);
  17. this._recipes = [];
  18. for(let i = 0; i < recipes.length; i++){
  19. this._recipes.push(new TransactionRecipe(
  20. recipes[i].recipe,
  21. recipes[i].quantity,
  22. parent
  23. ));
  24. }
  25. }
  26. get id(){
  27. return this._id;
  28. }
  29. get date(){
  30. return this._date;
  31. }
  32. get recipes(){
  33. return this._recipes;
  34. }
  35. /*
  36. Gets the quantity for a given ingredient
  37. */
  38. getIngredientQuantity(ingredient){
  39. let quantity = 0;
  40. let traverseSubIngredients = (current, main)=>{
  41. if(current.ingredient === main) return current.quantity;
  42. for(let i = 0; i < current.ingredient.subIngredients.length; i++){
  43. return traverseSubIngredients(current.ingredient.subIngredients[i], main);
  44. }
  45. return 0;
  46. }
  47. for(let i = 0; i < this._recipes.length; i++){
  48. const recipe = this._recipes[i].recipe;
  49. for(let j = 0; j < recipe.ingredients.length; j++){
  50. let actualIngredient = recipe.ingredients[j].ingredient;
  51. if(actualIngredient === ingredient){
  52. quantity += recipe.ingredients[j].quantity * this._recipes[i].quantity;
  53. }else{
  54. for(let k = 0; k < actualIngredient.subIngredients.length; k++){
  55. quantity += traverseSubIngredients(actualIngredient.subIngredients[i], ingredient) * this._recipes.quantity;
  56. }
  57. }
  58. }
  59. }
  60. return quantity;
  61. }
  62. }
  63. module.exports = Transaction;