Skip to content

Commit

Permalink
Combine x and ... in min, max, range
Browse files Browse the repository at this point in the history
Only call `vec_c` if dots are nonempty to stay fast in the empty case.
  • Loading branch information
brookslogan committed Jul 17, 2024
1 parent 920903d commit f8e15cc
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
12 changes: 12 additions & 0 deletions R/type-vctr.R
Original file line number Diff line number Diff line change
Expand Up @@ -545,6 +545,10 @@ vec_cast_or_na <- function(x, to, ...) {

#' @export
min.vctrs_vctr <- function(x, ..., na.rm = FALSE) {
if (dots_n(...) != 0L) {
x <- vec_c(x, ...)
}

if (vec_is_empty(x)) {
return(vec_cast_or_na(Inf, x))
}
Expand All @@ -566,6 +570,10 @@ min.vctrs_vctr <- function(x, ..., na.rm = FALSE) {

#' @export
max.vctrs_vctr <- function(x, ..., na.rm = FALSE) {
if (dots_n(...) != 0L) {
x <- vec_c(x, ...)
}

if (vec_is_empty(x)) {
return(vec_cast_or_na(-Inf, x))
}
Expand All @@ -587,6 +595,10 @@ max.vctrs_vctr <- function(x, ..., na.rm = FALSE) {

#' @export
range.vctrs_vctr <- function(x, ..., na.rm = FALSE) {
if (dots_n(...) != 0L) {
x <- vec_c(x, ...)
}

if (vec_is_empty(x)) {
return(vec_cast_or_na(c(Inf, -Inf), x))
}
Expand Down
12 changes: 12 additions & 0 deletions tests/testthat/test-type-vctr.R
Original file line number Diff line number Diff line change
Expand Up @@ -632,6 +632,18 @@ test_that("Summary generics behave identically to base for empty vctrs (#88)", {
)
})

test_that("methods combine `x` and `...` when generic expects them to (#1372)", {
x <- new_vctr(1)
y <- new_vctr(3)

expect_identical(min(x, y), x)
expect_identical(min(y, x), x)
expect_identical(max(x, y), y)
expect_identical(max(y, x), y)
expect_identical(range(x, y), c(x, y))
expect_identical(range(y, x), c(x, y))
})

test_that("generic predicates return logical vectors (#251)", {
x <- new_vctr(c(1, 2))
expect_identical(is.finite(x), c(TRUE, TRUE))
Expand Down

0 comments on commit f8e15cc

Please sign in to comment.