Skip to content

Commit

Permalink
Support atomic vector ptype in list_flatten()
Browse files Browse the repository at this point in the history
Allows implementing e.g. `rlang::flatten_int()`
  • Loading branch information
lionel- committed Aug 10, 2020
1 parent fab6e8d commit 75e8a48
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
12 changes: 9 additions & 3 deletions R/flatten.R
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,16 @@ list_flatten <- function(x, ..., ptype = x, name_spec = NULL) {
ellipsis::check_dots_empty()
list_assert(x)

# Wrap any non-list elements
out <- map_if(x, negate(vec_is_list), list)
if (vec_is_list(ptype)) {
# Wrap any non-list elements so all the elements to concatenate are lists
out <- map_if(x, negate(vec_is_list), list)
} else {
# Unchop all list elements so all the elements to concatenate are of type `ptype`
out <- map_if(x, vec_is_list, vec_unchop, ptype = ptype, name_spec = name_spec)
}

# Concatenate the elements (now all lists) in a single list
# Concatenate the elements (now all lists or all vectors) in a
# vector of type `ptype`
vec_unchop(out, ptype = ptype, name_spec = name_spec)
}

Expand Down
15 changes: 15 additions & 0 deletions tests/testthat/test-flatten.R
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,18 @@ test_that("list_flatten() creates output of type `ptype`", {
new_count_list(list(1, 2))
)
})

test_that("list_flatten() creates atomic vectors if requested", {
expect_identical(
list_flatten(list(1, list(2)), ptype = int()),
1:2
)
expect_identical(
list_flatten(
list(x = 1, y = list(foo = 2)),
ptype = int(),
name_spec = "{outer}_{inner}"
),
c(x = 1L, y_foo = 2L)
)
})

0 comments on commit 75e8a48

Please sign in to comment.