diff --git a/R/utils.R b/R/utils.R index 343a69a..1aafa17 100644 --- a/R/utils.R +++ b/R/utils.R @@ -9,7 +9,7 @@ add_tbl_class <- first_found_in <- - function(.x, domain, default = NA) { + function(.x, domain, default = NA_character_) { .out <- domain[domain %in% .x][1L] if (is.na(.out)) { .out <- default } .out @@ -18,9 +18,9 @@ first_found_in <- index_of_first_found_in <- function(.x, domain, default = NA_integer_) { - .out <- which(.x %in% domain)[1L] - if (is.na(.out)) { .out <- default } - .out + .out <- first_found_in(.x, domain) + if (is.na(.out)) { return(default) } + which(.x == .out) } diff --git a/tests/testthat/test-utils.R b/tests/testthat/test-utils.R index aca25f1..012fe63 100644 --- a/tests/testthat/test-utils.R +++ b/tests/testthat/test-utils.R @@ -25,3 +25,37 @@ test_that("format_force_data_link_data_frame() works as expected", { expect_type(result[[1L]], "character") expect_type(result[[2L]], "character") }) + +test_that("first_found_in() works as expected", { + # same order + .x <- c("A", "B", "C") + domain <- c("A", "C") + expect_equal(first_found_in(.x, domain), "A") + + # out of order + .x <- c("A", "B", "C") + domain <- c("B", "A") + expect_equal(first_found_in(.x, domain), "B") + + # `NA` if none found + .x <- c("a", "b") + domain <- c("source", "from", "sources", "start", "begin") + expect_equal(first_found_in(.x, domain), NA_character_) +}) + +test_that("index_of_first_found_in() works as expected", { + # same order + .x <- c("A", "B", "C") + domain <- c("A", "C") + expect_equal(index_of_first_found_in(.x, domain), 1L) + + # out of order + .x <- c("A", "B", "C") + domain <- c("B", "A") + expect_equal(index_of_first_found_in(.x, domain), 2L) + + # `NA` if none found + .x <- c("a", "b") + domain <- c("source", "from", "sources", "start", "begin") + expect_equal(index_of_first_found_in(.x, domain), NA_integer_) +})