Skip to content

Instantly share code, notes, and snippets.

@arraytools
Last active February 16, 2025 01:48
Show Gist options
  • Save arraytools/3ebff53e5f72c7299b0a8f78b0901578 to your computer and use it in GitHub Desktop.
Save arraytools/3ebff53e5f72c7299b0a8f78b0901578 to your computer and use it in GitHub Desktop.
Beyond Function Parameters: Using R Options for Dynamic Inputs. Demonstrate the idea behind the post "Using options() to inject a function’s internal variable for reproducible testing" https://brodrigues.co/posts/2025-02-13-testthat.html
calculate_total <- function(items) {
subtotal <- sum(items)
tax_rate <- getOption("TAX_RATE", default = 0.1) # Default 10% tax
total <- subtotal * (1 + tax_rate)
return(round(total, 2))
}
# Test the function with default tax rate
cart1 <- c(10, 20, 30)
print(calculate_total(cart1)) # Output: 66.00
# Set a different tax rate for testing
options(TAX_RATE = 0.15) # Set 15% tax rate
print(calculate_total(cart1)) # Output: 69.00
# Reset the option after testing
options(TAX_RATE = NULL)
print(calculate_total(cart1)) # Output: 66.00 (back to default)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment