Skip to content

Commit 480a461

Browse files
do pos_id computation by taking into account children too
1 parent fe4d47d commit 480a461

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

R/token-create.R

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,12 +65,30 @@ create_tokens <- function(tokens,
6565
#' @family token creators
6666
create_pos_ids <- function(pd, pos, by = 0.1, after = FALSE, n = 1) {
6767
direction <- ifelse(after, 1L, -1L)
68-
first <- pd$pos_id[pos] + by * direction
68+
first <- find_start_pos_id(pd, pos, by, direction, after)
6969
new_ids <- seq(first, to = first + direction * (n - 1) * by, by = by * direction)
7070
validate_new_pos_ids(new_ids, after)
7171
new_ids
7272
}
7373

74+
#' Find legit starting value for a new positional id
75+
#'
76+
#' Looks at the current nest as well as into its children (if necessary) to make
77+
#' sure the right id is returned. Otherise, ordering of tokens might not be
78+
#' preserved.
79+
#' @inheritParams create_pos_ids
80+
find_start_pos_id <- function(pd, pos, by, direction, after) {
81+
if (is.null(pd$child[[pos]])) {
82+
pd$pos_id[pos] + by * direction
83+
} else {
84+
85+
find_start_pos_id(
86+
pd$child[[pos]], if_else(after, nrow(pd$child[[pos]]), 1L),
87+
by, direction, after
88+
)
89+
}
90+
}
91+
7492
#' Validate sequence of new position ids
7593
#'
7694
#' Ids created with `after = TRUE` can have `pos_id` values between x.0 and

man/find_start_pos_id.Rd

Lines changed: 24 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)