Skip to content

Instantly share code, notes, and snippets.

@surjikal
Created December 30, 2013 22:36
Show Gist options
  • Save surjikal/8189419 to your computer and use it in GitHub Desktop.
Save surjikal/8189419 to your computer and use it in GitHub Desktop.
Some date range parser, a bit like elastic search.
###
unused, but cool
###
parseRange = do ->
isInfinity = (x) ->
x is Number.NEGATIVE_INFINITY or \
x is Number.POSITIVE_INFINITY or
/\-?infinity/i.test x
parseInfinity = (x) ->
sign = x.match(/(\-?)infinity/i)[1]
return if sign then Number.NEGATIVE_INFINITY \
else Number.POSITIVE_INFINITY
isYear = (x) ->
/\d{4}/.test x.toString()
parse = (datetimeStr) ->
datetimeStr = datetimeStr.toString().toLowerCase()
return parseInfinity(datetimeStr) if isInfinity(datetimeStr)
result = moment(datetimeStr).utc()
return result if result.isValid()
throw new Error("Could not parse time `#{datetimeStr}`.")
validate =
object: ({from, to}) ->
if isInfinity(from) and not to
throw new Error("Range property `to` is required when using unbounded `from` value `#{from}`.")
if isInfinity(to) and not from
throw new Error("Range property `from` is required when using unbounded `to` value `#{to}`.")
string: (from) ->
if not isYear(from)
throw new Error("A string range can only be a year (YYYY).")
normalize =
object: ({from, to}) ->
validate.object({from, to})
from: from or Number.NEGATIVE_INFINITY
to: to or Number.POSITIVE_INFINITY
string: (from) ->
validate.string(from)
from = parseInt(from)
to = from + 1
return {from, to}
(range) ->
range = do ->
isntObject = _.isNumber(range) or _.isString(range)
return normalize.string(range) if isntObject
return normalize.object(range)
range =
from: parse(range.from)
to: parse(range.to)
if range.to < range.from
throw new Error("Range value `to` cannot be smaller than `from` value.")
if isInfinity(range.from) and isInfinity(range.to)
return null
from: range.from.toISOString?() or range.from.toString()
to: range.to.toISOString?() or range.to.toString()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment