Skip to content

Commit

Permalink
Fix fraction handling in yieldCalculator
Browse files Browse the repository at this point in the history
  • Loading branch information
j0hannesr0th committed Jun 30, 2023
1 parent b7d2cb4 commit ebd4dca
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 10 deletions.
7 changes: 6 additions & 1 deletion src/components/RecipeView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -148,14 +148,19 @@
:key="'ingr' + idx"
:ingredient="ingredient"
:ingredient-has-correct-syntax="
/* yieldCalculator.isValidIngredientSyntax(ingredient) */
ingredientsWithValidSyntax[idx]
"
:recipe-ingredients-have-subgroups="
recipeIngredientsHaveSubgroups
"
:style="{
'font-style': ingredientsWithValidSyntax[idx]
? 'normal'
: 'italic',
}"
/>
</ul>

<div
v-if="!ingredientsSyntaxCorrect"
class="ingredient-parsing-error"
Expand Down
35 changes: 26 additions & 9 deletions src/js/yieldCalculator.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,29 +32,46 @@ function isIngredientsArrayValid(ingredients) {

function recalculateIngredients(ingredients, currentYield, originalYield) {
return ingredients.map((ingredient, index) => {
const fractionRegExp = /(\d+\s)?(\d+)\/(\d+)/
const matches = ingredient.match(fractionRegExp)

if (matches) {
const [
fullMatch,
wholeNumberPartRaw,
numeratorRaw,
denominatorRaw,
] = matches
const wholeNumberPart = wholeNumberPartRaw
? parseInt(wholeNumberPartRaw, 10)
: 0
const numerator = parseInt(numeratorRaw, 10)
const denominator = parseInt(denominatorRaw, 10)

const decimalAmount = wholeNumberPart + numerator / denominator
let newAmount = (decimalAmount / originalYield) * currentYield
newAmount = newAmount.toFixed(2).replace(/[.]00$/, "")

const newIngredient = ingredient.replace(fullMatch, newAmount)
return newIngredient
}

if (isValidIngredientSyntax(ingredient)) {
// For some cases, where the unit is not separated from the amount: 100g cheese
const possibleUnit = ingredient
.split(" ")[0]
.replace(/[^a-zA-Z]/g, "")
const amount = parseFloat(
ingredients[index].split(" ")[0].replace(",", ".")
)
const unitAndIngredient = ingredient.split(" ").slice(1).join(" ")

let newAmount = (amount / originalYield) * currentYield
newAmount = newAmount.toFixed(2).replace(/[.]00$/, "")

return `${newAmount}${possibleUnit} ${unitAndIngredient}`
}

const factor = currentYield / originalYield
const prefix = ((f) => {
if (f === 1) {
return ""
}
return `${f.toFixed(2)}x `
})(factor)
return `${prefix}${ingredient}`
return ingredient
})
}

Expand Down

0 comments on commit ebd4dca

Please sign in to comment.