R/assert.R

Defines functions assert_vals_not_null assert_vals_scalars assert_vals_not_empty assert_keys_unique assert_keys_not_empty assert_keys_match

# vals --------------------------------------------------------------------

assert_vals_not_null <- function(vals, keys) {
  null_vals <- map_lgl(vals, is.null)
  return_if(!any(null_vals))

  error_bullets(
    "Enum values cannot not be NULL.",
    "Found the following keys with NULL values:",
    keys[which(null_vals)]
  )
}

assert_vals_scalars <- function(vals, keys) {
  scalar <- map_lgl(vals, ~vctrs::vec_size(.x) == 1)
  return_if(all(scalar))
  error_bullets(
    "Enum values must be scalar.",
    "Found the following keys with non-scalar values:",
    keys[which(!scalar)]
  )
}

assert_vals_not_empty <- function(vals) {
  return_if(!rlang::is_empty(vals))
  error("Enums cannot be empty.")
}

# keys --------------------------------------------------------------------

assert_keys_unique <- function(keys) {
  dupes <- duplicated(keys)
  return_if(!any(dupes))
  error_bullets(
    "Enum keys cannot be duplicated.",
    "Found the following duplicated keys:",
    keys[dupes]
  )
}

assert_keys_not_empty <- function(keys) {
  invalid <- keys == ""
  return_if(!any(invalid))
  error_bullets(
    "Enum keys cannot be missing.",
    "Found the following values with missing keys:",
    paste0("..", which(invalid))
  )
}

assert_keys_match <- function(keys, choices) {
  matched <- keys %in% choices
  return_if(all(matched))
  error_bullets(
    "Enum keys cannot be modified.",
    "Found the following unknown keys:",
    keys[which(!matched)]
  )
}
shunsambongi/enum documentation built on Nov. 11, 2019, 6:46 a.m.