R/autofill.R

Defines functions Create_Autofill

Documented in Create_Autofill

#' Easily create an autofill list from a vector of items.
#'
#' Provide a vector list, receive a finished javascript file saved where you wish.
#' @param Entity_List A vector list of the entities to be placed in the autofill
#' @param File_Name What should the saved filename be? .js will automatically be appended.
#' @param Name_Autofill_Variable What is the name of the autofill variable in the associated javascript?
#' @param Use_Date Should the file have a date time prefix on the filename?
#' @export
#' @examples \dontrun{
#' Create_Autofill(Entity_List, File_Name = "Autofill", Name_Autofill_Variable = "unternehmen", Use_Date = TRUE)
#' }
#'
Create_Autofill <- function(Entity_List, File_Name = "Autofill", Name_Autofill_Variable = "unternehmen", Use_Date = TRUE){

  Right_Now <- format(Sys.time(), "%Y%m%d_%H%M%S")

  Entity_List <- data.table(Original = Entity_List)

  Clean_List <- Entity_List[, Autofill_Safe_Names := trimws(gsub("&amp","&",gsub("\u00A0", " ",gsub(" "," ",gsub("’","'",gsub(";",",",gsub('"',"'",Original)))))), which = "both")]%>%
    setorderv(cols = "Autofill_Safe_Names")%>%
    unique(by = "Autofill_Safe_Names")

  # This is to test encodings - not really a part of the function!
  # library(stringi)
  # testExcel_enc <- data.table(type = stri_enc_mark(Clean_List$Autofill_Safe_Names))
  # count <- testExcel_enc[, .N, by = "type"]

  Final_Text <- (paste0(paste0('var ',Name_Autofill_Variable,' = "', paste0(Clean_List[1]$Autofill_Safe_Names,";", collapse = ";")), paste0(Clean_List[2:nrow(Clean_List)]$Autofill_Safe_Names, collapse = ";"), paste0('".split(',"';');")))

  # Old way: (this meant that you had to use notepad++ to fix the encoding)
  # cat(paste0('var ',Name_Autofill_Variable,' = "', Clean_List[1]$Autofill_Safe_Names), Clean_List[2:nrow(Clean_List)]$Autofill_Safe_Names, paste0('".split(',"';');"), file = paste0(ifelse(Use_Date == TRUE, paste0(Right_Now,"_"),""),File_Name,".js"), sep = ";")

  ##########################################
  # Possibility (if the source isn't utf-8)
  # https://rlang.r-lib.org/reference/set_chr_encoding.html
  # Final_Text <- enc2utf8(Final_Text)
  ##########################################

  # new way: no reencoding necessary
  # https://stackoverflow.com/questions/10675360/utf-8-file-output-in-r
  writeLines(Final_Text, con = paste0(ifelse(Use_Date == TRUE, paste0(Right_Now,"_"),""),File_Name,".js"), sep = "", useBytes = TRUE)
}
bpresentati/surveyR documentation built on March 19, 2022, 3:40 a.m.