diff --git a/DESCRIPTION b/DESCRIPTION index 1dbd19f86b..8fcd49ec77 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -51,6 +51,7 @@ Imports: scales (>= 1.3.0), tidyselect (>= 1.2.1), vctrs, + withr, xml2 (>= 1.3.6) Suggests: digest (>= 0.6.31), @@ -70,8 +71,7 @@ Suggests: shiny (>= 1.9.1), testthat (>= 3.1.9), tidyr, - webshot2 (>= 0.1.0), - withr + webshot2 (>= 0.1.0) Config/Needs/coverage: officer Config/Needs/website: quarto ByteCompile: true diff --git a/NEWS.md b/NEWS.md index 60e307526d..b30d8ad165 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,7 @@ # gt (development version) +* The `random_id()` function now relies on `withr::with_seed()` and no longer affects the state of the random number generator in the global environment. + # gt 0.11.1 ## Breaking changes diff --git a/R/helpers.R b/R/helpers.R index db82ce6af9..050c532261 100644 --- a/R/helpers.R +++ b/R/helpers.R @@ -2926,7 +2926,19 @@ cell_style_structure <- function(name, obj, subclass = name) { #' @export random_id <- function(n = 10) { - paste(sample(letters, n, replace = TRUE), collapse = "") + # use last 5 digits of system time as seed + random_id_seed <- Sys.time() |> + as.numeric() |> + as.character() |> + # remove decimal point + sub("\\.", "", x = _) |> + # select last 5 digits + sub("\\d*(\\d{5}$)", "\\1", x = _) |> + as.numeric() + + withr::with_seed(random_id_seed, { + paste(sample(letters, n, replace = TRUE), collapse = "") + }) } latex_special_chars <- c( diff --git a/tests/testthat/test-helpers.R b/tests/testthat/test-helpers.R new file mode 100644 index 0000000000..82bb887ad5 --- /dev/null +++ b/tests/testthat/test-helpers.R @@ -0,0 +1,14 @@ +test_that("random_id() does not affect random seed", { + + withr::with_seed(123, { + r1 <- runif(1) + }) + + withr::with_seed(123, { + id <- random_id() + r2 <- runif(1) + }) + + expect_equal(r1, r2) + +})