R/utility.R

Defines functions expandingList

Documented in expandingList

#' Utility function for creating and adding to a list that dynamically resizes itself as items are added.
#' This should hopefully make the storage of results as the simulation is running more efficient.
#' @param capacity Starting size of the initial list. Everytime capacity is reached the list is doubled in size.
expandingList <- function(capacity = 10) {
  buffer <- vector('list', capacity)
  length <- 0
  
  methods <- list()
  
  methods$double.size <- function() {
    buffer <<- c(buffer, vector('list', capacity))
    capacity <<- capacity * 2
  }
  
  methods$add <- function(val) {
    if(length == capacity) {
      methods$double.size()
    }
    
    length <<- length + 1
    buffer[[length]] <<- val
  }
  
  methods$as.list <- function() {
    b <- buffer[0:length]
    return(b)
  }
  
  methods
}
rdinnager/nichefillr documentation built on Dec. 3, 2019, 7:13 a.m.