File: ihasNext.R

package info (click to toggle)
r-cran-itertools 0.1-3-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 316 kB
  • sloc: makefile: 2
file content (47 lines) | stat: -rw-r--r-- 889 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# This is based on code that was contributed by Hadley Wickham

hasNext.ihasNext <- function(obj, ...) {
  obj$hasNext()
}

ihasNext <- function(iterable) {
  it <- iter(iterable)

  if (inherits(it, 'ihasNext')) {
    it
  } else {
    cache <- NULL
    hasnext <- NA

    nextEl <- function() {
      if (! hasNx()) {
        stop('StopIteration', call.=FALSE)
      }

      hasnext <<- NA
      cache
    }

    hasNx <- function() {
      if (is.na(hasnext)) {
        tryCatch({
          cache <<- nextElem(it)
          hasnext <<- TRUE
        },
        error=function(e) {
          if (identical(conditionMessage(e), 'StopIteration')) {
            hasnext <<- FALSE
          } else {
            stop(e)
          }
        })
      }

      hasnext
    }

    obj <- list(nextElem=nextEl, hasNext=hasNx)
    class(obj) <- c('ihasNext', 'abstractiter', 'iter')
    obj
  }
}