-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdynamic-vector.R
83 lines (75 loc) · 2.09 KB
/
dynamic-vector.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#' An Amortized Vector
#'
#' This object stores a preallocated list. You can add objects to the list
#' with \code{add} and add lists to the list with \code{add_list}. When the
#' objects to be added exceed the dimensions of the list, the list is re-
#' allocated with double the size. This amortizes the runtime if you keep
#' growing the dynamic vector.
#'
#' Use this object if you need an object with a mutable states that you
#' keep growing. An example with be a list of RDF triples.
#'
#' @param add some method
#'
#'
#'
#'
#' @examples
#'
#' v = DynVector$new(3)
#' v$add("test")
#' @export
DynVector = R6::R6Class(
classname = "dynamic_vector",
private = list(
dynamic_vector = NULL,
last_item = 0
),
public = list(
initialize = function(size)
{
private$dynamic_vector = vector(mode = "list", length = size)
},
add = function(x)
{
current_item = private$last_item + 1
if (current_item > length(private$dynamic_vector)) {
# need to reallocate
b = DynVector$new(length(private$dynamic_vector)*2)
b$add_list(self$get())
b$add(x)
# is it possible to just replace self with b?
private$dynamic_vector = b$get()
private$last_item = length(private$dynamic_vector)
}
else {
private$dynamic_vector[[current_item]] = x
private$last_item = private$last_item + 1
}
},
add_list = function(l)
{
end_list = private$last_item + length(l)
if (end_list > length(private$dynamic_vector)) {
#reallocate
b = DynVector$new(length(private$dynamic_vector)*2)
b$add_list(self$get())
b$add_list(l)
# is it possible to just replace self with b?
private$dynamic_vector = b$get()
private$last_item = length(private$dynamic_vector)
}
else {
private$dynamic_vector[(private$last_item + 1):end_list] = l
private$last_item = end_list
}
},
get = function()
{
if (private$last_item == 0) {
return (list())
}
private$dynamic_vector[1:private$last_item]
}
)
)