R/staticimports.R

Defines functions str_pad

# Generated by staticimports; do not edit by hand.
# ======================================================================
# Imported from pkg:stringstatic
# ======================================================================

#' Duplicate and concatenate strings within a character vector
#'
#' Dependency-free drop-in alternative for `stringr::str_pad()`.
#'
#' @author Eli Pousson \email{eli.pousson@gmail.com}
#'   ([ORCID](https://orcid.org/0000-0001-8280-1706))
#'
#'   Alexander Rossell Hayes \email{alexander@rossellhayes.com}
#'   ([ORCID](https://orcid.org/0000-0001-9412-0457))
#'
#' @source Adapted from the [stringr](https://stringr.tidyverse.org/) package.
#'
#' @param string Input vector.
#'   Either a character vector, or something coercible to one.
#' @param width Minimum width of padded strings.
#' @param side Side on which padding character is added (left, right or both).
#' @param pad Single padding character (default is a space).
#' @param use_width If `FALSE`,
#'   use the length of the string instead of the width;
#'   see [str_width()]/[str_length()] for the difference.
#'
#' @return A character vector.
#' @noRd
str_pad <- function(
	string, width, side = c("left", "right", "both"), pad = " ", use_width = TRUE
) {
	if (!is.numeric(width)) {
		return(string[NA])
	}

	if (any(nchar(pad, type = "width") != 1)) {
		stop("each string in `pad` should consist of code points of total width 1")
	}

	side <- match.arg(side)

	nchar_type <- if (isTRUE(use_width)) "width" else "chars"
	string_width <- nchar(string, nchar_type)
	pad_width <- width - string_width
	pad_width[pad_width < 0] <- 0

	switch(
		side,
		"left" = paste0(strrep(pad, pad_width), string),
		"right" = paste0(string, strrep(pad, pad_width)),
		"both" = paste0(
			strrep(pad, floor(pad_width / 2)),
			string,
			strrep(pad, ceiling(pad_width / 2))
		)
	)
}

Try the wru package in your browser

Any scripts or data that you put into this service are public.

wru documentation built on May 29, 2024, 9:46 a.m.