class Sequence
  constructor:(@fn, @cb)->
    @times = 0
    @args = []

  next:(args)->
    unless nextArgs = @args.shift()
      nextFn = @cb
    else 
      nextFn = @next.bind @, nextArgs
    if @times--
      @fn.apply @, args.concat nextFn
    
  add:(args)->
    unless @times++
      process.nextTick @next.bind(@, args)
    else
      @args.push args

{slice} = []

module.exports = (fn, cb)->
  sequence = new Sequence fn, cb
  ->
    args = sequence.add slice.call arguments