Skip to content

Commit

Permalink
Merge pull request #244 from fa993/main
Browse files Browse the repository at this point in the history
Feature Request: Percentages
  • Loading branch information
printfn authored Nov 2, 2023
2 parents 5d7198c + f5efe68 commit bc53718
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
11 changes: 10 additions & 1 deletion core/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,16 @@ pub(crate) fn evaluate<I: Interrupt>(
return Ok(val);
}
}
eval!(*a)?.apply(*b, ApplyMulHandling::Both, scope, attrs, context, int)?
match (*a, *b) {
(a, Expr::Of(x, expr)) if x.as_str() == "%" => eval!(a)?
.handle_num(
|x| x.div(Number::from(100), int),
Expr::UnaryDiv,
scope.clone(),
)?
.apply(*expr, ApplyMulHandling::Both, scope, attrs, context, int)?,
(a, b) => eval!(a)?.apply(b, ApplyMulHandling::Both, scope, attrs, context, int)?,
}
}
Expr::ApplyFunctionCall(a, b) => {
eval!(*a)?.apply(*b, ApplyMulHandling::OnlyApply, scope, attrs, context, int)?
Expand Down
21 changes: 21 additions & 0 deletions core/tests/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2148,6 +2148,27 @@ fn five_percent_times_100() {
test_eval("5% * 100", "500%");
}

#[test]
fn five_percent_of_100() {
// Continuing the discussion in the previous test
// We handle the overloading in the evaluate function
// If we encounter an Of with a percent in the LHS
// Then we divide the LHS with 100 and multiply it with RHS
// Discarding the percent in the process

test_eval("5% of 100", "5");
}

#[test]
fn five_percent_of_200() {
test_eval("2 + 5% of 200", "12");
}

#[test]
fn five_percent_of_200_2() {
test_eval("(2 + 5)% of 200", "14");
}

#[test]
fn units_1() {
test_eval("0m + 1kph * 1 hr", "1000 m");
Expand Down

0 comments on commit bc53718

Please sign in to comment.