Skip to content

Instantly share code, notes, and snippets.

@PabRod
Created July 28, 2021 10:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PabRod/5bbe91548db0b6478962c8d5c3f6425d to your computer and use it in GitHub Desktop.
Save PabRod/5bbe91548db0b6478962c8d5c3f6425d to your computer and use it in GitHub Desktop.
Decorators in R
deco <- function(f) {
wrapper <- function(...) {
# <code prior to execution>
res <- f(...)
# <code after execution>
return(res)
}
return(wrapper)
}
deco <- function(f) {
wrapper <- function(...) {
# Optional: extract arguments
args <- list(...)
# <more code prior to execution>
res <- f(unlist(args))
# <code after execution>
return(res)
}
return(wrapper)
}
log1starg <- function(f, filename = 'loginput.txt') {
wrapper <- function(x, ...) {
# Before execution
write(x, file = filename, append = TRUE) # Log the first argument only
res <- f(x, ...)
return(res)
}
return(wrapper)
}
logger <- function(f, filename = 'log.txt') {
wrapper <- function(...) {
# Before execution
# Do nothing
res <- f(...)
# After execution
write(res, file = filename, append = TRUE)
return(res)
}
return(wrapper)
}
timer <- function(f) {
wrapper <- function(...) {
# Before execution
op <- options(digits.secs = 6) # Our example is fast. Increase time resolution
print(paste("Ini time:", Sys.time())) # Show the clock before execution
res <- f(...)
# After execution
print(paste("End time:", Sys.time())) # Show the clock after execution
return(res)
}
return(wrapper)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment