ranges in portions are handled correctly

This commit is contained in:
Alexander Bocken 2023-07-14 14:31:19 +02:00
parent 90895fb957
commit f8b5160f2d
Signed by: Alexander
GPG Key ID: 1D237BE83F9B05E8

View File

@ -58,18 +58,22 @@ function findGCD(a, b) {
return findGCD(b, a % b); return findGCD(b, a % b);
} }
// For portions, not sure whether to keep or let it be // "1-2 Kuchen (Durchmesser: 26cm", constant=2 -> "2-4 Kuchen (Durchmesser: 26cm)"
function multiplyFirstNumberInString(inputString, constant) { function multiplyFirstAndSecondNumbers(inputString, constant) {
const firstNumberRegex = /\d+(?:[\.,]\d+)?/; const regex = /(\d+(?:[\.,]\d+)?)(\s*-\s*\d+(?:[\.,]\d+)?)?/;
const match = inputString.match(firstNumberRegex); return inputString.replace(regex, (match, firstNumber, secondNumber) => {
if (match) { const numbersToMultiply = [firstNumber];
const number = match[0].includes(',') ? match[0].replace(/\./g, '').replace(',', '.') : match[0]; if (secondNumber) {
const multiplied = (parseFloat(number) * constant).toString(); numbersToMultiply.push(secondNumber.replace(/-\s*/, ''));
const rounded = parseFloat(multiplied).toString(); }
const result = match[0].includes(',') ? rounded.replace('.', ',') : rounded; const multipliedNumbers = numbersToMultiply.map(number => {
return inputString.replace(firstNumberRegex, result); const multiplied = (parseFloat(number) * constant).toString();
} const rounded = parseFloat(multiplied).toString();
return inputString; const result = number.includes(',') ? rounded.replace('.', ',') : rounded;
return result;
});
return multipliedNumbers.join('-')
});
} }
function adjust_amount(string, multiplier){ function adjust_amount(string, multiplier){
@ -130,7 +134,7 @@ button.selected{
<div class=ingredients> <div class=ingredients>
{#if data.portions} {#if data.portions}
<h3>Portionen:</h3> <h3>Portionen:</h3>
{@html convertFloatingPointToFraction(multiplyFirstNumberInString(data.portions, multiplier))} {@html convertFloatingPointToFraction(multiplyFirstAndSecondNumbers(data.portions, multiplier))}
{/if} {/if}
<h3>Menge anpassen:</h3> <h3>Menge anpassen:</h3>