Refactor quantity input parsing to handle additional units and improve conversion logic across inventory forms and recipe pages
This commit is contained in:
@@ -35,13 +35,24 @@ export default function InventoryForm({ products }: Props) {
|
||||
|
||||
function parseQuantityInput(input: string, defaultUnit: string) {
|
||||
const match = input.trim().match(/^([\d.,]+)\s*([a-zA-Z]*)$/);
|
||||
if (!match) return { quantity: NaN, unit: defaultUnit };
|
||||
let [, num, unit] = match;
|
||||
num = num.replace(',', '.');
|
||||
unit = unit || defaultUnit;
|
||||
if (defaultUnit === 'kg' && (unit === 'g' || unit === 'gram')) return { quantity: parseFloat(num) / 1000, unit: 'kg' };
|
||||
if (defaultUnit === 'g' && (unit === 'kg' || unit === 'kilogram')) return { quantity: parseFloat(num) * 1000, unit: 'g' };
|
||||
return { quantity: parseFloat(num), unit };
|
||||
if (!match) return { quantity: NaN, unit: defaultUnit };
|
||||
let [, num, unit] = match;
|
||||
num = num.replace(',', '.');
|
||||
unit = unit.toLowerCase() || defaultUnit;
|
||||
const value = parseFloat(num);
|
||||
// Konvertera alltid till defaultUnit
|
||||
if (defaultUnit === 'kg') {
|
||||
if (unit === 'g' || unit === 'gram') return { quantity: value / 1000, unit: 'kg' };
|
||||
if (unit === 'hg' || unit === 'hektogram') return { quantity: value / 10, unit: 'kg' };
|
||||
if (unit === 'kg' || unit === 'kilogram' || unit === '') return { quantity: value, unit: 'kg' };
|
||||
}
|
||||
if (defaultUnit === 'g') {
|
||||
if (unit === 'kg' || unit === 'kilogram') return { quantity: value * 1000, unit: 'g' };
|
||||
if (unit === 'hg' || unit === 'hektogram') return { quantity: value * 100, unit: 'g' };
|
||||
if (unit === 'g' || unit === 'gram' || unit === '') return { quantity: value, unit: 'g' };
|
||||
}
|
||||
// Lägg till fler konverteringar vid behov
|
||||
return { quantity: value, unit: defaultUnit };
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
Reference in New Issue
Block a user