Created
August 5, 2010 00:35
-
-
Save mdellavo/509033 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Chat(args) { | |
this.data = []; | |
this.callbacks = []; | |
this.args = args || []; | |
} | |
Chat.prototype.length = function() { | |
var rv = 0; | |
for(var i=0; i<this.data.length; i++) | |
rv += this.data[i].length; | |
return rv; | |
} | |
Chat.prototype.push = function(data) { | |
this.data.push(data); | |
this.consume(); | |
} | |
Chat.prototype.next = function(len, callback, args) { | |
this.callbacks.push([ len, callback, args || [] ]); | |
this.consume(); | |
} | |
Chat.prototype.consume = function() { | |
if(this.callbacks.length > 0) { | |
var length = this.length(); | |
var consumed_length = this.callbacks[0][0]; | |
var callback = this.callbacks[0][1]; | |
var args = this.args.concat(this.callbacks[0][2]); | |
if(length >= consumed_length) { | |
this.callbacks.pop(); | |
var data = this.data.join(""); | |
var consumed = data.substr(0, consumed_length); | |
var rest = data.substr(consumed_length); | |
this.data = [ rest ] | |
var this_ = this; | |
setTimeout.call(null, function() { | |
callback.apply(this_, args.concat([consumed]) ); | |
}, 0); | |
} | |
} | |
} | |
exports.Chat = Chat; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment