From 15aa3d9c1939ab9643462aeb870d35d27fd0a976 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Ver=C3=ADssimo?= <211358+averissimo@users.noreply.github.com> Date: Mon, 21 Oct 2024 16:39:37 +0100 Subject: [PATCH] `as_map()` keeps attributes (#186) Co-authored-by: Hadley Wickham --- NEWS.md | 1 + R/utils.R | 10 ++++++++-- tests/testthat/test-utils.R | 7 +++++++ 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/NEWS.md b/NEWS.md index 3c9b724..808074d 100644 --- a/NEWS.md +++ b/NEWS.md @@ -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). diff --git a/R/utils.R b/R/utils.R index 3f2f5dd..c69fef4 100644 --- a/R/utils.R +++ b/R/utils.R @@ -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) @@ -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 } diff --git a/tests/testthat/test-utils.R b/tests/testthat/test-utils.R index 6dbcebb..0740e76 100644 --- a/tests/testthat/test-utils.R +++ b/tests/testthat/test-utils.R @@ -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))