Skip to content

Instantly share code, notes, and snippets.

@mpjdem
Last active September 3, 2019 16:41
Show Gist options
  • Save mpjdem/d20ab2f674cd6158c106e76cc1e6bce9 to your computer and use it in GitHub Desktop.
Save mpjdem/d20ab2f674cd6158c106e76cc1e6bce9 to your computer and use it in GitHub Desktop.
'Strategy' design pattern in R
qsort <- function(inp, cfun) {
if (length(inp) > 1) {
cres <- cfun(inp, inp[[length(inp)]])
c(qsort(inp[cres < 0], cfun), inp[cres == 0], qsort(inp[cres > 0], cfun))
} else {
inp
}
}
users <- list(list(name = "John Doe", subscription = 0),
list(name = "Jane Doe", subscription = 1),
list(name = "John Dur", subscription = 1),
list(name = "Sara Der", subscription = 1))
alphabetic_sort <- function(uvec, uref) {
vec_names <- sapply(uvec, function(x) x$name)
vec_subs <- sapply(uvec, function(x) x$subscription)
equal_users <- vec_subs == uref$subscription & vec_names == uref$name
earlier_users <- vec_subs > uref$subscription | (vec_subs == uref$subscription & vec_names < uref$name)
later_users <- vec_subs < uref$subscription | (vec_subs == uref$subscription & vec_names > uref$name)
(!equal_users) * ((-1 * earlier_users) + (1 * later_users))
}
reverse_sort <- function(uvec, uref) {
vec_names <- sapply(uvec, function(x) x$name)
vec_subs <- sapply(uvec, function(x) x$subscription)
equal_users <- vec_subs == uref$subscription & vec_names == uref$name
earlier_users <- vec_subs > uref$subscription | (vec_subs == uref$subscription & vec_names > uref$name)
later_users <- vec_subs < uref$subscription | (vec_subs == uref$subscription & vec_names < uref$name)
(!equal_users) * ((-1 * earlier_users) + (1 * later_users))
}
qsort(users, alphabetic_sort)
qsort(users, reverse_sort)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment