Skip to content

Instantly share code, notes, and snippets.

@jonocarroll
Created June 7, 2024 04:17
Show Gist options
  • Save jonocarroll/4b98cd1d1081f594d70254b59e460653 to your computer and use it in GitHub Desktop.
Save jonocarroll/4b98cd1d1081f594d70254b59e460653 to your computer and use it in GitHub Desktop.
S3 Enums
enum <- function(...) {
vals <- if (is.null(...names())) {
setNames(seq_len(...length()), c(...))
} else {
c(...)
}
out <- new.env(parent = emptyenv())
list2env(as.list(vals), out)
lapply(names(vals), lockBinding, out)
lockEnvironment(out)
class(out) <- "enum"
out
}
print.enum <- function(x, ...) {
cat("An enum with", length(x) ,"levels:\n")
print(ls(x))
}
dirs <- enum("north", "east", "south", "west")
dirs
#> An enum with 4 levels:
#> [1] "east" "north" "south" "west"
dirs$north
#> [1] 1
dirs$down <- 5
#> Error in dirs$down <- 5: cannot add bindings to a locked environment
dirs$north <- 7
#> Error in dirs$north <- 7: cannot change value of locked binding for 'north'
"north" %in% names(dirs)
#> [1] TRUE
dirs <- enum("north" = 3, "east" = 4, "south" = 5, "west" = 6)
dirs
#> An enum with 4 levels:
#> [1] "east" "north" "south" "west"
dirs$north
#> [1] 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment