pgte/carrier — pull request #4 by stephank (2012-01-31 18:22:55+00:00)
Title: Simplify splitting logic.

I'm going to be bold here; this cuts a third in code in the main module. Tests pass. :)

The difference in thinking here is hidden in:

// get rid of last "" after last "\n"

That empty string can be considered the start of an unfinished line. The last element from the result of `split` will always be something unfinished / not terminated by a newline:

''.split('\n') # => [''] => buffer is ''
'foo'.split('\n') # => ['foo'] => buffer is 'foo'
'foo\n'.split('\n') # => ['foo', ''] => buffer is ''
'foo\nbar'.split('\n') # => ['foo', 'bar'] => buffer is 'bar'

So you can basically concat the buffer and new data, then reuse the last element as the buffer for the next run:

var lines = (buffer + data).split("\n");
buffer = lines.pop();

Only at the very end of the stream do we need to prevent emitting an empty line. That can be easily checked, the buffer will be the empty string from the last `split`.