Skip to content

Instantly share code, notes, and snippets.

@mythz
Created March 4, 2011 17:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mythz/855291 to your computer and use it in GitHub Desktop.
Save mythz/855291 to your computer and use it in GitHub Desktop.
Stand-alone version Google goog.string.StringBuffer for efficient string catenation on all browsers
var hasScriptEngine = 'ScriptEngine' in window;
var HAS_JSCRIPT = hasScriptEngine && window['ScriptEngine']() == 'JScript';
var IS_IE = HAS_JSCRIPT;
var StringBuffer = function(opt_a1, var_args) {
this.buffer_ = HAS_JSCRIPT ? [] : '';
if (opt_a1 != null) {
this.append.apply(this, arguments);
}
};
var p = StringBuffer.prototype;
p.set = function(s) {
this.clear();
this.append(s);
};
if (HAS_JSCRIPT) {
p.bufferLength_ = 0;
p.append = function(a1, opt_a2, var_args) {
if (opt_a2 == null) {
this.buffer_[this.bufferLength_++] = a1;
} else {
this.buffer_.push.apply((this.buffer_), arguments);
this.bufferLength_ = this.buffer_.length;
}
return this;
};
p.isEmpty = function() {
return this.bufferLength_ == 0;
}
} else {
p.append = function(a1, opt_a2, var_args) {
this.buffer_ += a1;
if (opt_a2 != null) {
for (var i = 1; i < arguments.length; i++) {
this.buffer_ += arguments[i];
}
}
return this;
};
p.isEmpty = function() {
return !this.buffer_;
}
}
p.clear = function() {
if (HAS_JSCRIPT) {
this.buffer_.length = 0;
this.bufferLength_ = 0;
} else {
this.buffer_ = '';
}
};
p.getLength = function() {
return this.toString().length;
};
p.toString = function() {
if (HAS_JSCRIPT) {
var str = this.buffer_.join('');
this.clear();
if (str) {
this.append(str);
}
return str;
} else {
return (this.buffer_);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment