/
wait_until.R
64 lines (61 loc) · 1.36 KB
/
wait_until.R
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#' Wait a Number of Signals
#'
#' These bricks encapsulate \code{n} stops: wait for a sequence of \code{n}
#' signals. \code{wait_until} also traps and untraps the required signals.
#'
#' @param n number of \code{wait} activities to chain.
#' @inheritParams simmer::send
#'
#' @return \code{wait_n} returns \code{n} times \code{\link[simmer:send]{wait}}.
#' \code{wait_until} also adds \code{\link[simmer:send]{trap}} and
#' \code{\link[simmer:send]{untrap}} at the beginning and end, respectively,
#' of the chain of \code{wait}s (see examples below).
#' @export
#'
#' @examples
#' ## These are equivalent:
#' trajectory() %>%
#' wait_n(3)
#'
#' trajectory() %>%
#' wait() %>%
#' wait() %>%
#' wait()
#'
wait_n <- function(.trj, n=1) {
if (!n) return(.trj)
stopifnot(n >= 1)
.trj %>%
wait() %>%
wait_n(n-1)
}
#' @rdname wait_n
#' @export
#'
#' @examples
#' ## These are equivalent:
#' trajectory() %>%
#' wait_until("green")
#'
#' trajectory() %>%
#' trap("green") %>%
#' wait() %>%
#' untrap("green")
#'
#' ## These are equivalent:
#' trajectory() %>%
#' wait_until(c("one", "another"), 2)
#'
#' trajectory() %>%
#' trap(c("one", "another")) %>%
#' wait() %>%
#' wait() %>%
#' untrap(c("one", "another"))
#'
wait_until <- function(.trj, signals, n=1) {
stopifnot(n >= 1)
.trj %>%
trap(signals) %>%
wait_n(n) %>%
untrap(signals)
}