Skip to content

Commit

Permalink
Flatten lists when possible. (#68)
Browse files Browse the repository at this point in the history
Only for chr right now. Will need to refactor and generalize this.
  • Loading branch information
jonthegeek authored Feb 23, 2024
1 parent 0df6ea3 commit aff36c2
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 2 deletions.
4 changes: 2 additions & 2 deletions DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Package: stbl
Title: Stabilize Function Arguments
Version: 0.0.0.9000
Version: 0.0.0.9001
Authors@R:
person("Jon", "Harmon", , "[email protected]", role = c("aut", "cre"),
comment = c(ORCID = "0000-0003-4781-4346"))
Expand All @@ -24,4 +24,4 @@ Config/testthat/edition: 3
Config/testthat/parallel: true
Encoding: UTF-8
Roxygen: list(markdown = TRUE)
RoxygenNote: 7.2.3
RoxygenNote: 7.3.0
2 changes: 2 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ S3method(to_chr,default)
S3method(to_chr,list)
S3method(to_fct,"NULL")
S3method(to_fct,character)
S3method(to_fct,data.frame)
S3method(to_fct,default)
S3method(to_fct,factor)
S3method(to_fct,list)
S3method(to_int,"NULL")
S3method(to_int,character)
S3method(to_int,complex)
Expand Down
7 changes: 7 additions & 0 deletions R/to_chr.R
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,13 @@ to_chr.list <- function(x,
x_arg = caller_arg(x),
call = caller_env(),
x_class = object_type(x)) {
flat <- unlist(x)
if (length(flat) == length(x)) {
if (length(flat) == 1) {
flat <- flat[[1]]
}
return(to_chr(flat))
}
.stop_cant_coerce(
from_class = x_class,
to_class = "character",
Expand Down
15 changes: 15 additions & 0 deletions tests/testthat/test-to_chr.R
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,21 @@ test_that("to_chr() works for other things", {
)
})

test_that("to_chr() tries to flatten lists", {
expect_identical(
to_chr(list("a", "b")),
c("a", "b")
)
expect_identical(
to_chr(list(1, 2)),
c("1", "2")
)
expect_identical(
to_chr(list("a")),
c("a")
)
})

test_that("to_chr() fails gracefully for weird cases", {
wrapper <- function(wrapper_val, ...) {
return(to_chr(wrapper_val, ...))
Expand Down

0 comments on commit aff36c2

Please sign in to comment.