Skip to content

Commit

Permalink
Merge commit '15aa3d9c1939ab9643462aeb870d35d27fd0a976'
Browse files Browse the repository at this point in the history
  • Loading branch information
hadley committed Oct 21, 2024
2 parents 0553d86 + 15aa3d9 commit 1063dab
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,6 +1,7 @@
# waldo (development version)

* waldo gains basic support for S7 objects (#200).
* `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 @@ -160,9 +160,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 @@ -173,6 +174,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 1063dab

Please sign in to comment.