Skip to content

Commit

Permalink
fix: keep attributes on as_map
Browse files Browse the repository at this point in the history
  • Loading branch information
averissimo committed Nov 20, 2023
1 parent e31e97d commit 9dd2c9f
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
3 changes: 2 additions & 1 deletion R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ compact <- function(x) {
}

as_map <- function(x) {
x_attr <- attributes(x) %||% list()
# Remove nulls
is_null <- vapply(x, is.null, logical(1))
x <- x[!is_null]
Expand All @@ -170,7 +171,7 @@ as_map <- function(x) {
idx[is_named] <- idx[is_named][order(nx[is_named])]
x <- x[idx]
}

attributes(x) <- utils::modifyList(x_attr, attributes(x))
x
}

Expand Down
7 changes: 7 additions & 0 deletions tests/testthat/test-utils.R
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
test_that("as_map() keeps attributes", {
expect_equal(
as_map(structure(list(b = 1, a = 2), attr1 = "a")),
structure(list(a = 2, b = 1), attr1 = "a")
)
})

test_that("as_map() leaves unnnamed components alone", {
expect_equal(as_map(c(c = 5, 2, b = 3, 4, a = 1)), c(a = 1, 2, b = 3, 4, c = 5))
expect_equal(as_map(c(c = 3, b = 2, a = 1)), c(a = 1, b = 2, c = 3))
Expand Down

0 comments on commit 9dd2c9f

Please sign in to comment.