Skip to content

Instantly share code, notes, and snippets.

@eddyrene
Created August 11, 2021 02:43
Show Gist options
  • Save eddyrene/355067cd95e58e2db580aa30df0ea6d0 to your computer and use it in GitHub Desktop.
Save eddyrene/355067cd95e58e2db580aa30df0ea6d0 to your computer and use it in GitHub Desktop.
getDiscount <- function(currency.input, date.input)
{ # Computes the percentage of discount to apply based on date and currency
#
#Args:
# currency.input = character of the currency
# date.input = the current date
#
# Returns:
# The percentage of discount to apply on the sum of products
#
# defining percentages for each case
discount.date <- 0.5
discount.eur <- 0.2
discount.usd <- 0.25
#Dataframe with currencies defined
name <- c("EUR","USD")
value <- c(discount.eur,discount.usd)
currencies <- data.frame(name,value)
#defining specific date
date.selected <- as.Date("2020-11-27")
disc.currency <- currencies[currencies$name == currency.input,]
#evaluating type of discount to apply
discount <- ifelse(date.selected == date.input, discount.date,
ifelse(nrow(disc.currency)>0,disc.currency$value,0))
return(discount)
}
totalPrice <- function(order, currency = "EUR", date = Sys.Date()){
# Computes the sum of all product's of a order after applying discount based
# on the currency and date
#
# Args:
# order: Dataframe with products to be calculated
# currency: character variable, indicates currency to be used
# date: Current date, used for
#
# Returns:
# The sum of products on order after applying a discount
#
# Error handling NULL input and type validation
if((is.null(dim(order))) || !is.character(currency)) {
stop("Order is null or input types invalid")
}
total <- 0
# Validating if the dataframe is empty
if(nrow(order)> 0)
{
discount <- getDiscount(currency, date)
tryCatch(
{
#Cleaning the dataframe from duplicates, negatives, NA values
order <- unique(order)
prices <- order[paste0("price_", currency)]
prices <- prices[prices>0]
prices <- prices[!is.na(prices)]
total <- sum(prices * (1-discount))
},
error = function(e){
#verifying if the currency selected exist on the dataframe
stop("The currency is not found!")
}
)
}
else{
warning("Order without products!")
}
return(total)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment