Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: more complete handling of * and / combinations for currency #63

Merged
merged 2 commits into from
Feb 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions baselines/currency/currency-math.txt
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,6 @@ true
true
false
true
$44
$44
$11
2 changes: 1 addition & 1 deletion baselines/currency/square-dollars.errors.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
Operand must be a number.
Cannot multiply two currencies.
[line 1]
5 changes: 5 additions & 0 deletions examples/currency/currency-math.lox
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,8 @@ print $1,234 == $1,234;
print $1,234 >= $1,234;
print $1,234 == €1,234; // false!
print $1,234 != €1,234;

print $22 * 2;
print 2 * $22;

print $22 / 2;
24 changes: 22 additions & 2 deletions src/interpreter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ function applyToNumOrCurrency(
return fn(val);
}

function getNumber(val: CurrencyValue | number): number {
return isCurrency(val) ? val.value : val;
}

function assertUnreachable(x: never): never {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
throw new Error(`Unreachable code reached! ${x}`);
Expand Down Expand Up @@ -96,13 +100,29 @@ export class Interpreter {
checkSameNumberOperands(operator, pair);
return applyOperatorToPair(pair, (a, b) => a - b);
case "/":
// currency/scalar is OK but scalar/currency is not.
checkNumberOrCurrencyOperand(operator, left);
checkNumberOperand(operator, right);
return applyToNumOrCurrency(left, (v) => v / right);
case "*":
// Everything but currency*currency is OK.
checkNumberOrCurrencyOperand(operator, left);
checkNumberOperand(operator, right);
return applyToNumOrCurrency(left, (v) => v * right);
checkNumberOrCurrencyOperand(operator, right);
const curR = isCurrency(right);
const value = getNumber(left) * getNumber(right);
if (isCurrency(left)) {
if (curR) {
throw new RuntimeError(operator, "Cannot multiply two currencies.");
} else {
return { currency: left.currency, value };
}
} else {
if (curR) {
return { currency: right.currency, value };
} else {
return value;
}
}
case "+":
// This looks kinda funny!
if (typeof left === "string" && typeof right === "string") {
Expand Down
Loading