Skip to content

Commit

Permalink
as_map() keeps attributes (#186)
Browse files Browse the repository at this point in the history
Co-authored-by: Hadley Wickham <[email protected]>
  • Loading branch information
averissimo and hadley authored Oct 21, 2024
1 parent 8f8dedc commit 15aa3d9
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# waldo (development version)

* `as_map()` now preserves attributes (#185).
* `compare()` can now distinguish between objects that differ only in the value of their S4 bit (#189).
* Double comparisons now always display one more digit than the absolute minimum necessary (#141).
* waldo no longer imports tibble and rematch2 (@olivroy, #196).
Expand Down
10 changes: 8 additions & 2 deletions R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -156,9 +156,10 @@ compact <- function(x) {
}

as_map <- function(x) {
attr <- attributes(x)

# Remove nulls
is_null <- vapply(x, is.null, logical(1))
x <- x[!is_null]
x <- compact(x)

# Sort named components, preserving positions of unnamed
nx <- names2(x)
Expand All @@ -169,6 +170,11 @@ as_map <- function(x) {
x <- x[idx]
}

# Restore attributes (which might have been lost by [)
new_attr <- attributes(x)
attr[names(new_attr)] <- new_attr
attributes(x) <- attr

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 15aa3d9

Please sign in to comment.