Last active
September 3, 2019 16:41
-
-
Save mpjdem/d20ab2f674cd6158c106e76cc1e6bce9 to your computer and use it in GitHub Desktop.
'Strategy' design pattern in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
As discussed here:
https://www.mpj-analytics.co.uk/2019/09/04/design-patterns-r-strategy/
Inspired by:
http://mishadoff.com/blog/clojure-design-patterns/#episode-2-strategy