Skip to content

Instantly share code, notes, and snippets.

@moiristo
Last active October 9, 2015 09:08
Show Gist options
  • Save moiristo/34baad4da9ddd767f431 to your computer and use it in GitHub Desktop.
Save moiristo/34baad4da9ddd767f431 to your computer and use it in GitHub Desktop.
BoundedEventBuffer CS class: buffers event calls until a given condition is met
class @BoundedEventBuffer
constructor: ( options = {} ) ->
@buffer = []
@processConditionMet = false
@processing = false
{ @name, @bufferSize, @processWhen, @interval } = options
@name = options.name ? 'AnonymousEventBuffer'
@bufferSize = options.bufferSize ? 100
@processWhen = options.processWhen ? (-> true)
if @processWhen
@interval = options.interval ? 1000
@checkInterval = setInterval (=> @_process()), @interval
isEmpty: -> @buffer.length == 0
triggerProcessConditionMet: () ->
unless @processConditionMet
@processConditionMet = true
@_processBuffer()
push: (eventFunction, args) ->
event = { trigger: eventFunction, args: args }
if @processConditionMet && @isEmpty()
@_processEvent event
true
else if @buffer.length < @bufferSize
@buffer.push event
@_process() if @processConditionMet && !@processing
true
else
console.log "#{@name} full, ignoring event..." if console?
false
_process: ->
if !@processConditionMet && @processWhen()
clearInterval @checkInterval
@processConditionMet = true
if @processConditionMet then @_processBuffer() else false
_processBuffer: ->
@processing = true
@_processEvent bufferedEvent while bufferedEvent = @buffer.shift()
@processing = false
@isEmpty()
_processEvent: (event) -> event.trigger.apply(null, event.args)
# Example:
# buf = new BoundedEventBuffer(name: 'MyEventBuffer', bufferSize: 20, processWhen: (-> window.test == true ))
# buf.push ((num) -> console.log("Event #{num}")), [i] for i in [1..30]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment