Chomp <- R6::R6Class(
"chomp",
public = list(
string = "",
current = "",
result = list(),
initialize = function(string) {
self$string <- string
self$current <- string
},
skip = function(n) {
stopifnot(n <= nchar(self$current))
self$current <- substr(self$current, n + 1, nchar(self$current))
self
},
digits = function(n, name) {
value <- substr(self$current, 1, n)
self$current <- substr(self$current, n + 1, nchar(self$current))
stopifnot(!is.na(as.numeric(value)))
self$result[[name]] <- as.numeric(value)
self
},
reset = function() {
self$current <- self$string
self$result <- list()
self
}
)
)
date <- Chomp$new("12-02-2020")
date$
digits(2, "month")$
skip(1)$
digits(2, "day")$
skip(1)$
digits(4, "year")$
result
#> $month
#> [1] 12
#>
#> $day
#> [1] 2
#>
#> $year
#> [1] 2020
Created on 2020-12-02 by the reprex package (v0.3.0)