mpneuried
6/24/2013 - 8:41 AM

Get the count of timestamps based on a given timeframe.

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 )