I was discussing with @Airy, @Nige_S and @peternlewis about how some Text Functions work in this thread. Although we shared a few CALCULATE() examples to highlight some of its unique behaviors/quirks, I believe there are better use cases that truly showcase its benefits.
To start, I created an "Example Macro" that takes advantage of features in CALCULATE() that aren’t accessible through the Calculate action/token. While the macro could be made more efficient using other methods, @Airy was interested in exploring “possible tricks” we can add to our toolbox for solving new types of problems.
CALCULATE Function example.kmmacros (11.6 KB)
EXPLANATION
This Keyboard Maestro macro calculates discounts by dynamically constructing and evaluating mathematical expressions using the CALCULATE() function.
The central calculation is performed in this action:
CALCULATE(purchaseAmount * Tier%TierID%Discount)
Here’s how it works:
The macro dynamically creates a variable name inside the CALCULATE function by concatenating three parts:
-
The static text "
Tier
" -
The value of the
TierID
variable (which is set to "1", "2", "3", or "Employee" earlier in the loop) -
The static text "
Discount
"
For instance:
-
If a purchase qualifies for the third tier, the TierID variable becomes 3. The expression resolves to
purchaseAmount * Tier3Discount
-
For an employee, TierID is set to Employee, and the expression resolves to
purchaseAmount * TierEmployeeDiscount
The CALCULATE() function evaluates this dynamically generated string, retrieves the correct discount percentage from the corresponding variable (e.g., Tier3Discount or TierEmployeeDiscount), and completes the multiplication. This method allows a single, adaptable action to handle dynamic discount rules.
It would be nice if you could share other examples of the CALCULATE() Function =)