Skip to content

Instantly share code, notes, and snippets.

@gadenbuie
Forked from tjmahr/chomp.md
Last active December 2, 2020 17:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gadenbuie/6404722941350c3ea7f9ba9e211cc8d7 to your computer and use it in GitHub Desktop.
Save gadenbuie/6404722941350c3ea7f9ba9e211cc8d7 to your computer and use it in GitHub Desktop.
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)

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