File: itimer.R

package info (click to toggle)
r-cran-iterators 1.0.14-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 600 kB
  • sloc: sh: 29; makefile: 2
file content (30 lines) | stat: -rw-r--r-- 572 bytes parent folder | download | duplicates (6)
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
library(iterators)

# Returns an iterator that limits another iterator based on time
itimer <- function(it, time) {
  it <- iter(it)
  start <- proc.time()[[3]]

  nextEl <- function() {
    current <- proc.time()[[3]]
    if (current - start >= time)
      stop('StopIteration')

    nextElem(it)
  }

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

# Create a iterator that counts for one second
it <- itimer(icount(Inf), 1)
tryCatch({
  repeat {
    print(nextElem(it))
  }
},
error=function(e) {
  cat('timer expired\n')
})