Skip to content

Instantly share code, notes, and snippets.

@tjmahr
Created December 2, 2020 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tjmahr/cb37f149c3ec06f404d917e14190bf58 to your computer and use it in GitHub Desktop.
Save tjmahr/cb37f149c3ec06f404d917e14190bf58 to your computer and use it in GitHub Desktop.
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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment