We start by loading the Line class.

Line <- R6::R6Class(
  "Line",

  public = list(

    initialize = function(id){
      private$.id <- id
      private$.queue <- datastructures::queue()
    },

    add_agent = function(agent){
      invisible(datastructures::insert(private$.queue, agent))
      invisible(self)
    },

    remove_agent = function(n = 1){
      removed <- mapply(function(i){
        datastructures::pop(private$.queue)
      }, 1:n)

      #idea for this came from
      #https://stackoverflow.com/questions/33004238/r-removing-null-elements-from-a-list
      return(Filter(Negate(is.null), removed))
    }
  ),

  active = list(
    id = function(value){
      if(missing(value)){
        private$.id
      } else {
        stop("Cannot set `$id` after instantiation\n")
      }
    },

    num_of_agents = function(value){
      if(missing(value)){
        datastructures::size(private$.queue)
      } else{
        stop("Cannot set `$num_of_events`, use add_agent() or remove_agent()\n")
      }
    },

    queue = function(value){
      if(missing(value)){
        private$.queue
      } else {
        stop("Cannot set `$queue`, use add_event() or remove_event()")
      }
    }
  ),

  private = list(
    .id = -1,
    .queue = NULL
  )
)

Testing

We now perform the unit testing.

Creating a new line

#create a line
l1 <- Line$new(1)

#check default config
stopifnot(l1$id == 1)
stopifnot(datastructures::size(l1$queue) == 0)

#if we made it here, we passed
print("Pass: Creating new line")
## [1] "Pass: Creating new line"

Adding agents to line

#create a line
l1 <- Line$new(1)

#add a single agent 
l1$add_agent(1)

#check that the agent was added
stopifnot(l1$num_of_agents == 1)

#add 3 more agents using method chaining and check queue size
l1$add_agent(2)$add_agent(3)$add_agent(4)
stopifnot(l1$num_of_agents == 4)

#confirm the order added is the order in queue
for(i in 1:4){
  stopifnot(datastructures::pop(l1$queue) == i)
}

#confirm queue is empty now
stopifnot(l1$num_of_agents == 0)

#if we make it here, the test has passed
print("Pass: Adding agents to line")
## [1] "Pass: Adding agents to line"

Removing agents from line

#create a line
l1 <- Line$new(1)

#remove the default (n = 1)
result <- l1$remove_agent()

stopifnot(length(result) == 0)

#add 3  agents using method chaining and check queue size
l1$add_agent(2)$add_agent(3)$add_agent(4)

#remove two items
result <- l1$remove_agent(2)

#check that we removed the two first items (2,3)
stopifnot(length(result) == 2)
stopifnot(result == list(2,3))

#remove the remaining agent
invisible(l1$remove_agent())

#now try to remove another
result <- l1$remove_agent()

#and confirm that no results where returned
stopifnot(length(result) == 0)

#if we make it here, the test has passed
print("Pass: Removing agents from line")
## [1] "Pass: Removing agents from line"