Skip to content

Commit

Permalink
fix: unit error
Browse files Browse the repository at this point in the history
  • Loading branch information
ArmanNik committed Dec 15, 2023
1 parent 94e4c1a commit 0a007a3
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions src/lib/helpers/unit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,18 @@ export function createValueUnitPair<T = string>(initialValue = 0, units: Unit<T>

unit.subscribe((newValue, prev) => {
value.update((v) => {
const unitInBase = v * units.find((u) => u.name === prev).value;
return unitInBase / units.find((u) => u.name === newValue).value;
const prevUnit = units.find((u) => u.name === prev);
const newUnit = units.find((u) => u.name === newValue);

// If either unit is not found, just return the current value
if (!prevUnit || !newUnit) {
return v;
}

const unitInBase = v * prevUnit.value;
return unitInBase / newUnit.value;
});
});

return {
value,
unit,
Expand Down

0 comments on commit 0a007a3

Please sign in to comment.