Skip to content

Commit

Permalink
keep duplicates on modify, fixes r-lib#97, fixes r-lib#107
Browse files Browse the repository at this point in the history
  • Loading branch information
jchrom committed Apr 22, 2022
1 parent db69718 commit 936db3c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
25 changes: 22 additions & 3 deletions R/utils.R
Expand Up @@ -21,22 +21,41 @@ bullets_with_header <- function(header, x) {
cli::cli_li(paste0("{.field ", names(x), "}: ", vals))
}

modify_list <- function(.x, ...) {
modify_list <- function(.x, ..., .compact = TRUE) {
dots <- list2(...)
if (length(dots) == 0) return(.x)

if (!is_named(dots)) {
abort("All components of ... must be named")
}
.x[names(dots)] <- dots
out <- compact(.x)

out <- replace2(.x, dots) %>% compact()

if (length(out) == 0) {
names(out) <- NULL
}

out
}

# Replace elements in `x` with elements in `y`, preserving the original ordering
# where applicable, and preserving duplicates found in `y`.
replace2 <- function(x, y) {

for (nm in unique(names(y))) {

xi <- which(names(x) == nm)
yi <- which(names(y) == nm)

x[xi[seq_along(xi) <= length(yi)]] <- y[yi[seq_along(yi) <= length(xi)]]

x[xi[seq_along(xi) > length(yi)]] <- NULL

x <- c(x, y[yi[seq_along(yi) > length(xi)]])
}

x
}

sys_sleep <- function(seconds) {
check_number(seconds, "`seconds`")
Expand Down
5 changes: 5 additions & 0 deletions tests/testthat/test-utils.R
Expand Up @@ -9,6 +9,11 @@ test_that("modify list adds, removes, and overrides", {
expect_snapshot(modify_list(x, a = 1, 2), error = TRUE)
})

test_that("`modify_list()` preserves duplicates in `y`", {
x <- list(x = 1, y = 2)
expect_equal(modify_list(x, y = 3, y = 4), list(x = 1, y = 3, y = 4))
})

test_that("can check arg types", {
expect_snapshot(error = TRUE, {
check_string(1, "x")
Expand Down

0 comments on commit 936db3c

Please sign in to comment.