Skip to content

Instantly share code, notes, and snippets.

@hadley
Last active October 22, 2017 18:28
Show Gist options
  • Save hadley/7572036 to your computer and use it in GitHub Desktop.
Save hadley/7572036 to your computer and use it in GitHub Desktop.
frame <- function(from = -Inf, to = 0) {
if (from >= to) stop("from must be less than to", call. = FALSE)
dir <- function(x) if (x < 0) "PRECEDING" else "FOLLOWING"
val <- function(x) if (is.finite(x)) as.integer(x) else "UNBOUNDED"
bound <- function(x) {
if (x == 0) return("CURRENT ROW")
paste(val(x), dir(x))
}
if (to == 0) {
bound(from)
} else {
paste0("BETWEEN ", bound(from), " AND ", bound(to))
}
}
@max-mapper
Copy link

in JS just for fun:

function frame(from, to) {
  if (!from) from = -Infinity
  if (!to) to = 0
  if (to === 0) console.log(bound(from))
  else console.log("BETWEEN", bound(from), "AND", bound(to))
}

function dir(x) {
  return x < 0 ? "PRECEDING" : "FOLLOWING"
}

function val(x) {
  return isFinite(x) ? x : "UNBOUNDED"
}

function bound(x) {
  if (x === 0) return "CURRENT ROW"
  return val(x) + ' ' + dir(x)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment