Skip to content

Commit a0cf386

Browse files
committed
Added optional stop to icount. #39
1 parent 57536e7 commit a0cf386

File tree

3 files changed

+27
-5
lines changed

3 files changed

+27
-5
lines changed

R/icount.r

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,20 +12,23 @@
1212
#' @param start sequence's initial value
1313
#' @param step sequence's step size
1414
#' @return sequence's iterator
15-
#'
15+
#'
1616
#' @examples
1717
#' it <- icount()
1818
#' iterators::nextElem(it)
1919
#' iterators::nextElem(it)
2020
#' iterators::nextElem(it)
21-
#'
21+
#'
2222
#' it2 <- icount(start=5.5, step=1.5)
2323
#' iterators::nextElem(it2)
2424
#' iterators::nextElem(it2)
2525
#' iterators::nextElem(it2)
26-
icount <- function(start=0, step=1) {
26+
icount <- function(start=0, step=1, stop=NULL) {
2727
start <- as.numeric(start)
2828
step <- as.numeric(step)
29+
if (!is.null(stop)) {
30+
stop <- as.numeric(stop)
31+
}
2932

3033
if (length(start) != 1) {
3134
stop("'start' must be a numeric value of length 1")
@@ -37,11 +40,15 @@ icount <- function(start=0, step=1) {
3740
current_val <- start - step
3841
nextElem <- function() {
3942
current_val <<- current_val + step
43+
44+
if (!is.null(stop) && current_val > stop) {
45+
stop("StopIteration", call.=FALSE)
46+
}
47+
4048
current_val
4149
}
4250

4351
it <- list(nextElem=nextElem)
4452
class(it) <- c("abstractiter", "iter")
4553
it
4654
}
47-

man/icount.Rd

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
\alias{icount}
55
\title{Iterator of neverending numeric sequence with initial value and step size}
66
\usage{
7-
icount(start = 0, step = 1)
7+
icount(start = 0, step = 1, stop = NULL)
88
}
99
\arguments{
1010
\item{start}{sequence's initial value}

tests/testthat/test-icount.r

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,18 @@ test_that("icount works with a decimal step size", {
4747
i <- nextElem(it)
4848
expect_equal(i, 46.5)
4949
})
50+
51+
test_that("icount works with the optional stop", {
52+
it <- icount(stop=5)
53+
expect_equal(0:5, unlist(as.list(it)))
54+
})
55+
56+
test_that("icount works with a given initial value and a stop", {
57+
it <- icount(start=42, stop=50)
58+
expect_equal(42:50, unlist(as.list(it)))
59+
})
60+
61+
test_that("icount works with a stop and decimal step size", {
62+
it <- icount(start=42, step=1.5, stop=50)
63+
expect_equal(seq(42, 50, by=1.5), unlist(as.list(it)))
64+
})

0 commit comments

Comments
 (0)