library(magrittr)
chomp_setup <- function(x) {
list(.string = x, .current = x, .last = "")
}
chomp_n_skip <- function(x, n) {
# would need to guard against n > length
x$.last <- substr(x$.current, 1, n)
x$.current <- substr(x$.current, n + 1, nchar(x))
x
}
chomp_n_digits <- function(x, n, name) {
x$.last <- substr(x$.current, 1, n)
x$.current <- substr(x$.current, n + 1, nchar(x))
stopifnot(!is.na(as.numeric(x$.last)))
x[[name]] <- x$.last
x
}
chomp_list <- function(x, ...) {
x[c(...)]
}
date <- "12-02-2020"
chomp_setup(date) %>%
chomp_n_digits(2, "month") %>%
chomp_n_skip(1) %>%
chomp_n_digits(2, "day") %>%
chomp_n_skip(1) %>%
chomp_n_digits(4, "year") %>%
chomp_list("year", "month", "day")
#> $year
#> [1] "2020"
#>
#> $month
#> [1] "12"
#>
#> $day
#> [1] "02"
Created on 2020-12-02 by the reprex package (v0.3.0)