Skip to content

Commit

Permalink
fix logic of first_found functions and test (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
cjyetman committed Dec 24, 2023
1 parent 92b4edb commit 003e81e
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
8 changes: 4 additions & 4 deletions R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
}


Expand Down
34 changes: 34 additions & 0 deletions tests/testthat/test-utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -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_)
})

0 comments on commit 003e81e

Please sign in to comment.