pfmc-assessments/nwfscSurvey

Duplicated code for converting to hex

Closed this issue · 1 comments

This is a suggestion that can be completely ignored ...
I noticed that there is duplicated code that converts ASCII to hex in the pull_*() functions. For example, in pull_catch()

nwfscSurvey/R/pull_catch.R

Lines 119 to 129 in d371e6f

species_str <- paste0(
"%22",stringr::str_replace_all(species[1]," ","%20"),"%22"
)
if(length(species) > 1) {
for(i in 2:length(species)) {
species_str <- paste0(
species_str, "%2C", paste0(
"%22",stringr::str_replace_all(species[i]," ","%20"),"%22"))
}
}

I think we should create a helper function, e.g., see below, because I could not find an existing function that does what we need, though I am sure that there is one somewhere in cyberland.

  convert_to_hex_string <- function(x) {
    hex_comma <- toupper(paste0("%", charToRaw(",")))
    hex_quote <- paste0("%", charToRaw('"'))
    hex_space <- paste0("%", charToRaw(" "))
    stopifnot(inherits(x, "character"))

    # Convert spaces to %20
    x_no_spaces <- gsub(pattern = " ", replacement = hex_space, x)

    # Wrap each string in quotes with %22 and
    # separate strings with %2C, which is a comma
    out <- paste0(hex_quote, x_no_spaces, hex_quote, collapse = hex_comma)

    return(out)
  }

The following example uses the above code and ends up with the same result as what is currently in the code:

species <- c("lingcod", "sablefish", "pacific cod")
species_str <- "%22lingcod%22%2C%22sablefish%22%2C%22pacific%20cod%22"
convert_to_hex_string(species) == species_str
TRUE

This was a great suggestion. Thank you for providing code to make this addition easy.