Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use withr::with_seed() in random_id() #1916

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ Imports:
scales (>= 1.3.0),
tidyselect (>= 1.2.1),
vctrs,
withr,
xml2 (>= 1.3.6)
Suggests:
digest (>= 0.6.31),
Expand All @@ -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
Expand Down
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
14 changes: 13 additions & 1 deletion R/helpers.R
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
14 changes: 14 additions & 0 deletions tests/testthat/test-helpers.R
Original file line number Diff line number Diff line change
@@ -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)

})
Loading