UNPKG

968 Btext/coffeescriptView Raw
1events = require('events')
2
3class Aggregator
4 constructor: (name, implementation, opts) ->
5 @name = name
6 @implementation = implementation
7 @opts = opts
8 @implementation.init.call(this, @opts)
9 @cachedValue = null
10 @events = new events.EventEmitter()
11 on: (event, callback) ->
12 @events.on(event, callback)
13 push: (time, values) ->
14 values = [values] unless Array.isArray(values)
15 for value in values
16 value = @opts.before.call(this, value) if @opts.before
17 @implementation.push.call(this, time, value) unless value is undefined
18 oldValue = @cachedValue
19 @events.emit('change', @cachedValue, oldValue) unless @compute() is oldValue
20 compute: ->
21 @cachedValue = @implementation.compute.call(this)
22 @cachedValue = @opts.after.call(this, @cachedValue) if @opts.after
23 @cachedValue
24 value: ->
25 @cachedValue
26
27exports.buildAggregator = (name, implementation)-> ((opts) -> new Aggregator(name, implementation, opts))
\No newline at end of file