caring-band v1.4.3
Statistical Object
Allows to easily store: count, min, max, last, sum, sum-of-squares.
This is inspired by CouchDB's _stats built-in reduce function.
Results are stored as big-rational numbers.
bigRat = require 'big-rational'Each statistical object stored offers the following fields:
count, the number of items submittedmin, the numerically smallest item submittedmax, the numerically largest item submittedlast, the most recent item submittedsum, the numerical sum of all items submittedsumsqr, the sum of squares of each item submitted
A new item is submitted either:
- by using
add(number); by using
add(), in which case the number is assumed to be 0 (and onlycountis meaningful).class CaringBandData constructor: -> @count = new bigRat 0 @min = null @max = null @last = null @sum = new bigRat 0 @sumsqr = new bigRat 0
add: (number) -> number ?= 0 number = new bigRat number @last = number @count = @count.add 1 if not @min? or @min.greater number @min = number if not @max? or number.greater @max @max = number @sum = @sum.add number @sumsqr = @sumsqr.add number.times number this toJSON: (decimals) -> text = [] for own k,v of this when v? text.push """ "#{k}": #{v.toDecimal decimals} """ "{#{text.join ', '}}"
Storage Object
The module exports a storage object which allows you to:
add(key,item): add a new numerical item to a key's statistical object; returns the new statistical object;add(key): count a new entry; the value is assumed to be zero; returns the new statistical object;get(key): retrieve the statistical object defined above;delete(key): delete the statisitcal object for the key.
Keys might be any JSON-compatible types. Non-string keys are converted to strings using JSON.stringify.
The storage object is also an EventEmitter.
{EventEmitter} = require 'events'
class CaringBand extends EventEmitter
constructor: ->
@data = {}
add: (key,number) ->
if typeof key isnt 'string'
key = JSON.stringify key
@data[key] ?= new CaringBandData()
value = @data[key].add numberIt will emit add when a value is updated.
@emit 'add', {key,number:value.last,value}
get: (key) ->
if typeof key isnt 'string'
key = JSON.stringify key
@data[key]
delete: (key) ->
if typeof key isnt 'string'
key = JSON.stringify key
delete @data[key]It will emit delete when a value is deleted.
@emit 'delete', {key}
toJSON: (precision) ->
hash = []
for own key,value of @data
do (key,value) ->
hash.push (JSON.stringify key) + ':' + value.toJSON precision
'{' + (hash.join ',') + '}'
module.exports = CaringBand
module.exports.data = CaringBandData