mirror of
https://github.com/rstudio/shiny.git
synced 2026-04-07 03:00:20 -04:00
Add sortByName function
This commit is contained in:
14
R/utils.R
14
R/utils.R
@@ -206,6 +206,20 @@ mergeVectors <- function(a, b) {
|
||||
x[!drop_idx]
|
||||
}
|
||||
|
||||
# Sort a vector by the names of items. If there are multiple items with the
|
||||
# same name, preserve the original order of those items. For empty
|
||||
# vectors/lists/NULL, return the original value.
|
||||
sortByName <- function(x) {
|
||||
if (anyUnnamed(x))
|
||||
stop("All items must be named")
|
||||
|
||||
# Special case for empty vectors/lists, and NULL
|
||||
if (length(x) == 0)
|
||||
return(x)
|
||||
|
||||
x[order(names(x))]
|
||||
}
|
||||
|
||||
# Wrapper around list2env with a NULL check. In R <3.2.0, if an empty unnamed
|
||||
# list is passed to list2env(), it errors. But an empty named list is OK. For
|
||||
# R >=3.2.0, this wrapper is not necessary.
|
||||
|
||||
@@ -129,6 +129,31 @@ test_that("anyUnnamed works as expected", {
|
||||
expect_true(anyUnnamed(x))
|
||||
})
|
||||
|
||||
test_that("sortByName works as expected", {
|
||||
# Error if any unnamed elements
|
||||
expect_error(sortByName(c("a", "b")))
|
||||
expect_error(sortByName(list(a=1, 2)))
|
||||
|
||||
expect_identical(sortByName(NULL), NULL)
|
||||
expect_identical(sortByName(numeric(0)), numeric(0))
|
||||
expect_identical(sortByName(character(0)), character(0))
|
||||
# Empty unnamed list
|
||||
expect_identical(sortByName(list()), list())
|
||||
# Empty named list
|
||||
expect_identical(sortByName(list(a=1)[0]), list(a=1)[0])
|
||||
|
||||
expect_identical(sortByName(list(b=1, a=2)), list(a=2, b=1))
|
||||
expect_identical(sortByName(list(b=1)), list(b=1))
|
||||
|
||||
# Ties are resolved by using original order
|
||||
expect_identical(sortByName(list(b=1, a=2, b=3)), list(a=2, b=1, b=3))
|
||||
expect_identical(sortByName(list(b=3, a=2, b=1)), list(a=2, b=3, b=1))
|
||||
|
||||
# Make sure atomic vectors work
|
||||
expect_identical(sortByName(c(b=1, a=2)), c(a=2, b=1))
|
||||
expect_identical(sortByName(c(b=1, a=2, b=3)), c(a=2, b=1, b=3))
|
||||
})
|
||||
|
||||
test_that("Callbacks fire in predictable order", {
|
||||
cb <- Callbacks$new()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user