Skip to content

Instantly share code, notes, and snippets.

@mpneuried
Last active December 18, 2015 21:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpneuried/5848625 to your computer and use it in GitHub Desktop.
Save mpneuried/5848625 to your computer and use it in GitHub Desktop.
Get the count of timestamps based on a given timeframe.
###
**IMPORTANT** Make shure moment.js is available.
**ARGUMENTS**
* `timestamps` *( Array )*:An arry of timestamps.
* `type` *( String )*: A moment time type like `minute`, `hour`, `day`
* `pastCursor` *( Number )*: A number to define the maximum time to the past. If lower than `0` all given timestamps will be returned.
###
countBy = ( timestamps, type = "hour", pastCursor = -1 )=>
_iDivider = moment( 0 ).add( type, 1 ).valueOf()
_mNow = moment().endOf(type)
_now = Math.ceil( _mNow.valueOf() / _iDivider )
if pastCursor > 0
_tsPast = _mNow.add( type, pastCursor * -1 ).valueOf()
_ret = []
_counts = {}
for _ts in timestamps
_k = ( _now - Math.ceil( _ts / _iDivider ) )
if _counts[ _k ]?
_counts[ _k ] = _counts[ _k ] + 1
else
_counts[ _k ] = 1
for _subtract in ( Object.keys( _counts ) ).sort( ( a, b )->b-a )
_time = ( _now - _subtract - 1 ) * _iDivider
if pastCursor <= 0 or _time > _tsPast
_ret.push
ts: _time
count: _counts[_subtract]
return _ret
# ##################
# TEST
# create some test data
now = Date.now()
_5min = 1000 * 60 * .5
ts = for i in [1..800]
now - _5min * i
# helper to test shuffled timestamps
shuffle = (a) ->
i = a.length
while --i > 0
j = ~~(Math.random() * (i + 1)) # ~~ is a common optimization for Math.floor
t = a[j]
a[j] = a[i]
a[i] = t
a
# returns an array of objects with `ts` as start time ( based on the `type` ) and the count within the timeframe
# EXAMPLE 1: get the standard behaviour. Count timestamps by hour
console.log countBy( ts )
# EXAMPLE 2: get a count by minutes, but only 20 Minutes back in time
console.log countBy( shuffle(ts), "minute", 20 )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment