summaryrefslogtreecommitdiffstats
path: root/R/normalize.R
diff options
context:
space:
mode:
authorMurilo Ijanc <[email protected]>2026-07-26 12:42:37 -0300
committerMurilo Ijanc <[email protected]>2026-07-26 12:42:37 -0300
commit11d49bc25eb1643f1b742f9527212d8781f2e0de (patch)
treebae1cb090cbf6c9f82ab5abbaf1194206f92f539 /R/normalize.R
downloadr-11d49bc25eb1643f1b742f9527212d8781f2e0de.tar.gz
Initial importv0.1.0
Diffstat (limited to 'R/normalize.R')
-rw-r--r--R/normalize.R43
1 files changed, 43 insertions, 0 deletions
diff --git a/R/normalize.R b/R/normalize.R
new file mode 100644
index 0000000..e54c0ef
--- /dev/null
+++ b/R/normalize.R
@@ -0,0 +1,43 @@
+#' Return the 8 digits of a CEP, accepting the mask
+#'
+#' @description
+#' `"01001-000"`, `"01001000"`, `"01001.000"` and `" 01001-000 "` all become
+#' `"01001000"`.
+#'
+#' This runs **before** any request: a 7-digit CEP is the caller's bug, and
+#' spending a round trip for the server to say so wastes both sides' time.
+#'
+#' @param value A length-one character vector. Numbers are rejected on
+#' purpose: `1001000` has already lost the leading zero that makes
+#' `"01001000"` a CEP. Convert with `sprintf("%08d", x)` first.
+#'
+#' @return The 8 digits, as a length-one character vector.
+#'
+#' @section Conditions:
+#' Signals [cepis_invalid_cep][cepis_conditions] unless exactly 8 digits
+#' remain.
+#'
+#' @examples
+#' normalize_cep("01001-000")
+#'
+#' @export
+normalize_cep <- function(value) {
+ if (!is.character(value) || length(value) != 1L || is.na(value)) {
+ stop(invalid_cep_error(
+ paste0(
+ "CEP must be a length-one character vector, got ",
+ class(value)[1L], " of length ", length(value)
+ ),
+ value = value
+ ))
+ }
+
+ cleaned <- gsub("[-. ]", "", trimws(value))
+ if (!grepl("^[0-9]{8}$", cleaned)) {
+ stop(invalid_cep_error(
+ paste0("CEP must be 8 digits, got \"", value, "\""),
+ value = value
+ ))
+ }
+ cleaned
+}