From d8692386ef1ab62e84df021c16d5291f6a299f02 Mon Sep 17 00:00:00 2001 From: Ernest Guevarra Date: Tue, 12 Mar 2024 09:21:41 +0000 Subject: [PATCH] refactor get_colours to search from more fields --- R/utils.R | 18 ++++++++++++++++-- man/get_colour.Rd | 1 + tests/testthat/test-utils.R | 3 +++ 3 files changed, 20 insertions(+), 2 deletions(-) create mode 100644 tests/testthat/test-utils.R diff --git a/R/utils.R b/R/utils.R index 2ce5758..6371b33 100644 --- a/R/utils.R +++ b/R/utils.R @@ -40,6 +40,7 @@ print.palette <- function(x, ...) { #' get_colours(model = "rgb") #' get_colours(pattern = "orange") #' get_colours(pattern = c("orange", "brown"), named = TRUE) +#' get_colours(pattern = c("orange", "GREEN", "Blue")) #' #' @rdname get_colour #' @export @@ -55,9 +56,15 @@ get_colour <- function(pattern = NULL, ## Determine if there is something specific to search for ---- if (!is.null(pattern)) { - ## Get colours vector ---- - paleta_cols <- df[c("name", model)][stringr::str_detect(df$name, pattern = pattern), ] + ## Get list for searchable fields ---- + search_fields <- list(df[["organisation"]], df[["name"]], df[["code"]]) + ## Get colours vector ---- + paleta_cols <- lapply(search_fields, stringr::str_detect, pattern = pattern) |> + (\(x) do.call(cbind, x))() |> + rowSums() |> + (\(x) ifelse(x == 0, FALSE, TRUE))() |> + (\(x) df[x, c("name", model)])() if (named) { paleta_cols <- paleta_cols |> @@ -95,6 +102,13 @@ get_colours <- function(pattern = NULL, if (is.null(pattern)) { paleta_cols <- get_colour(pattern = pattern, model = model, named = named) } else { + ## Get permutations of pattern ---- + pattern <- pattern |> + c(tolower(pattern)) |> + c(toupper(pattern)) |> + c(stringr::str_to_title(pattern)) |> + unique() + paleta_cols <- lapply( X = pattern, FUN = get_colour, model = model, named = named ) |> diff --git a/man/get_colour.Rd b/man/get_colour.Rd index 902a5c8..4ceadd8 100644 --- a/man/get_colour.Rd +++ b/man/get_colour.Rd @@ -39,5 +39,6 @@ get_colours() get_colours(model = "rgb") get_colours(pattern = "orange") get_colours(pattern = c("orange", "brown"), named = TRUE) +get_colours(pattern = c("orange", "GREEN", "Blue")) } diff --git a/tests/testthat/test-utils.R b/tests/testthat/test-utils.R new file mode 100644 index 0000000..35950b6 --- /dev/null +++ b/tests/testthat/test-utils.R @@ -0,0 +1,3 @@ +# Tests for utility functions -------------------------------------------------- + +testthat::expect_type(get_colours(pattern = "Blue"), "character")