Skip to content

Commit

Permalink
add sep argument to str_dup
Browse files Browse the repository at this point in the history
closes #487

Adds a sep argument to str_dup. Becasue this is not supported by stri_dup, do separately and use lapply to go through strings.
  • Loading branch information
edward-burn committed Aug 15, 2024
1 parent d681e45 commit f555ba4
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 3 deletions.
19 changes: 17 additions & 2 deletions R/dup.R
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,29 @@
#'
#' @inheritParams str_detect
#' @param times Number of times to duplicate each string.
#' @param sep String to insert between each duplicate.
#' @return A character vector the same length as `string`/`times`.
#' @export
#' @examples
#' fruit <- c("apple", "pear", "banana")
#' str_dup(fruit, 2)
#' str_dup(fruit, 1:3)
#' str_c("ba", str_dup("na", 0:5))
str_dup <- function(string, times) {
str_dup <- function(string, times, sep = NULL) {
vctrs::vec_size_common(string = string, times = times)
stri_dup(string, times)
if(is.null(sep)){
stri_dup(string, times)
} else {
# stri_dup does not currently support sep
check_string(sep)
lapply(seq_along(string), function(i) {
if (length(times) == 1) {
paste(rep(string[i], times), collapse = sep)
} else {
paste(rep(string[i], times[i]), collapse = sep)
}
}) |>
rlang::flatten_chr()
}

}
4 changes: 3 additions & 1 deletion man/str_dup.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 17 additions & 0 deletions tests/testthat/test-dup.R
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,20 @@ test_that("0 duplicates equals empty string", {
test_that("uses tidyverse recycling rules", {
expect_error(str_dup(1:2, 1:3), class = "vctrs_error_incompatible_size")
})

test_that("uses sep argument", {
expect_equal(str_dup("a", 3, sep = ";"), "a;a;a")
expect_equal(str_dup("abc", 2, sep = "-"), "abc-abc")
expect_equal(str_dup("a", 3, sep = ";"), "a;a;a")
expect_equal(str_dup("abc", 2, sep = "-"), "abc-abc")
expect_equal(str_dup(c("a", "b"), 2, sep = "x"), c("axa", "bxb"))
expect_equal(str_dup(c("aa", "bb", "ccc"), c(2, 3, 4), sep = ";"),
c("aa;aa", "bb;bb;bb", "ccc;ccc;ccc;ccc"))

expect_error(str_dup("a", 3, sep = 1))
expect_error(str_dup("a", 3, sep = c("-", ";")))
expect_error(str_dup(c("aa", "bb"), c(2, 3, 4), sep = ";"))
expect_error(str_dup(c("aa", "bb", "cc"), c(2, 3), sep = ";"))

})

0 comments on commit f555ba4

Please sign in to comment.