Skip to content

Commit

Permalink
Add the .validate_logical_scalar() internal helper function.
Browse files Browse the repository at this point in the history
  • Loading branch information
mcol committed Feb 10, 2025
1 parent 146acc5 commit 0fcb61f
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
22 changes: 22 additions & 0 deletions R/internals_RLum.R
Original file line number Diff line number Diff line change
Expand Up @@ -1335,6 +1335,28 @@ SW <- function(expr) {
}
}

#' @title Validate logical scalar variables
#'
#' @param val [numeric] (**required**): value to validate
#' @param null.ok [logical] (*with default*): whether a `NULL` value should be
#' considered valid (`FALSE` by default)
#' @param name [character] (*with default*): variable name to report in case
#' of error: if specified, it's reported as is; if not specified it's
#' inferred from the name of the variable tested and reported with
#' quotes.
#'
#' @md
#' @noRd
.validate_logical_scalar <- function(val, null.ok = FALSE, name = NULL) {
if (missing(val) || is.null(val) && null.ok)
return()
if (!is.logical(val) || length(val) != 1 || is.na(val)) {
if (is.null(name))
name <- sprintf("'%s'", all.vars(match.call())[1])
.throw_error(name, " should be a single logical value")
}
}

#' Check that a suggested package is installed
#'
#' Report a message with installation instructions if a suggested package
Expand Down
19 changes: 19 additions & 0 deletions tests/testthat/test_internals.R
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,25 @@ test_that("Test internals", {
expect_error(.validate_positive_scalar(NA, int = TRUE, name = "The variable"),
"The variable should be a positive integer")

## .validate_logical_scalar() ---------------------------------------------
expect_silent(.validate_logical_scalar())
expect_silent(.validate_logical_scalar(TRUE))
expect_silent(.validate_logical_scalar(FALSE))
expect_silent(.validate_logical_scalar(NULL, null.ok = TRUE))

expect_error(.validate_logical_scalar(test <- "a"),
"'test' should be a single logical value")
expect_error(.validate_logical_scalar(test <- NULL),
"'test' should be a single logical value")
expect_error(.validate_logical_scalar(iris),
"'iris' should be a single logical value")
expect_error(.validate_logical_scalar(c(TRUE, FALSE), name = "'var'"),
"'var' should be a single logical value")
expect_error(.validate_logical_scalar(0, name = "'var'"),
"'var' should be a single logical value")
expect_error(.validate_logical_scalar(NA, name = "The variable"),
"The variable should be a single logical value")

## .require_suggested_package() -------------------------------------------
expect_true(.require_suggested_package("utils"))
expect_error(.require_suggested_package("error"),
Expand Down

0 comments on commit 0fcb61f

Please sign in to comment.