Skip to content

Commit

Permalink
Implement parseIngredient algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
shovanch committed May 26, 2018
1 parent 4027480 commit 1367d9e
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 6 deletions.
8 changes: 2 additions & 6 deletions src/js/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,6 @@ elements.searchResultsPages.addEventListener("click", e => {
/**
* RECIPE CONTROLLER
**/
/* const r = new Recipe(46956);
r.getRecipe();
console.log(r);
r.calcTime();
r.calcServings(); */

const controlRecipe = async () => {
// Get recipe ID from url
Expand All @@ -80,6 +74,7 @@ const controlRecipe = async () => {
try {
// Get recipe data
await state.recipe.getRecipe();
state.recipe.parseIngredients();

// Calculate servings and time
state.recipe.calcTime();
Expand All @@ -88,6 +83,7 @@ const controlRecipe = async () => {
console.log(state.recipe);
} catch (error) {
alert("Error in Recipeview");
console.log(error);
}

// Render recipe
Expand Down
80 changes: 80 additions & 0 deletions src/js/models/Recipe.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,84 @@ export default class Recipe {
calcServings() {
this.servings = 4;
}

parseIngredients() {
const unitsLong = [
"tablespoons",
"tablespoon",
"teaspoons",
"teaspoon",
"ounces",
"ounce",
"cups",
"pounds"
];
const unitsShort = [
"tbsp",
"tbsp",
"tsp",
"tsp",
"oz",
"oz",
"cup",
"pound"
];

// process the ingredients array
const newIngredients = this.ingredients.map(el => {
// 1. Standardize units
let ingredient = el.toLowerCase();
unitsLong.forEach((unit, i) => {
ingredient = ingredient.replace(unit, unitsShort[i]);
});

// 2. Remove parentheses
ingredient = ingredient.replace(/ *\([^)]*\) */g, " ");

// 3. Parse ingredients into count, unit, ingredient
// split the array items
const ingArr = ingredient.split(" ");
const unitIndex = ingArr.findIndex(arrEl => unitsShort.includes(arrEl));

let objIng;
if (unitIndex > -1) {
// unit exits
// cut the elements the before the unit and store in an array
const arrCount = ingArr.slice(0, unitIndex);

let count;
// there is single digit
if (arrCount.length === 1) {
count = eval(ingArr[0].replace("-", "+"));
} else {
count = eval(ingArr.slice(0, unitIndex).join("+"));
}

objIng = {
count,
unit: ingArr[unitIndex],
ingredient: ingArr.slice(unitIndex + 1).join(" ")
};
} else if (parseInt(ingArr[0], 10)) {
// no unit, but a number
objIng = {
count: parseInt(ingArr[0], 10),
unit: "",
ingredient: ingArr.slice(1).join(" ")
};
} else if (unitIndex === -1) {
// unit doesnt exits
objIng = {
count: 1,
unit: "",
ingredient
};
}

return objIng;
});

// set the ingredients as the ingredients property
this.ingredients = newIngredients;
}
}

0 comments on commit 1367d9e

Please sign in to comment.