Skip to content

Commit

Permalink
Expand tests
Browse files Browse the repository at this point in the history
  • Loading branch information
t-kalinowski committed Sep 3, 2024
1 parent f0219ce commit eafccb1
Showing 1 changed file with 39 additions and 19 deletions.
58 changes: 39 additions & 19 deletions tests/iteration.R
Original file line number Diff line number Diff line change
Expand Up @@ -4,46 +4,66 @@
## These tests pass with both compiler::enableJIT(0) and compiler::enableJIT(3)

sequence_generator_factory <- function(start, end, step = 1L) {
if(missing(end)) {
if (missing(end)) {
end <- start
start <- 1L
}
stopifnot(length(start) == 1L,
length(end) == 1L,
length(stop) == 1L)
length(step) == 1L)

function() {
if (start > end)
return(NULL) # iterator exhausted

function(){
if(start > end) return(NULL)
on.exit(start <<- start + step)
start
}
}


x <- structure(list(), class = 'foo')
as.iterable.foo <- function(x) 1:3
as.iterable.foo <- function(x) c("a", "b", "c")

## pass an object with an `as.iterable` method to `for`
counter <- 0L
for(i in x){
counter <- counter + 1L
print(i)
## pass to `for` an object with an `as.iterable()` method
observed <- textConnection(NULL, "w", local = TRUE)
for (elem in x) {
writeLines(elem, observed)
}
stopifnot(i == 3L, counter == 3L)
stopifnot(
identical(elem, "c"),
identical(textConnectionValue(observed), c("a", "b", "c"))
)

observed <- textConnection(NULL, "w", local = TRUE)

## pass to `for` a closure
for (elem in sequence_generator_factory(4)) {
writeLines(paste("elem =", elem), observed)
}

## pass a function to `for`
for(i in sequence_generator_factory(4))
cat("i = ", i, "\n")

stopifnot(i == 4L)
stopifnot(
identical(elem, 4L),
identical(
textConnectionValue(observed),
c("elem = 1", "elem = 2", "elem = 3", "elem = 4")
))

## pass to `for` an object with an `as.iterable` method that returns a function
observed <- textConnection(NULL, "w", local = TRUE)

## pass to `for` an object with an `as.iterable()` method that returns a closure
as.iterable.foo <- function(x) {
sequence_generator_factory(11, 13)
}

for(i in x)
cat("i = ", i, "\n")
for(elem in x) {
writeLines(paste("elem =", elem), observed)
}

stopifnot(i == 13)
stopifnot(
identical(elem, 13L),
identical(
textConnectionValue(observed),
c("elem = 11", "elem = 12", "elem = 13")
))

0 comments on commit eafccb1

Please sign in to comment.