Last active
September 28, 2015 22:48
-
-
Save myaumyau/1508335 to your computer and use it in GitHub Desktop.
[js]StringBuilder
This file contains hidden or 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(){ | |
/** | |
* コンストラクタ | |
* @class 可変型の文字列を表します。 | |
* @constructor | |
*/ | |
StringBuilder = function() { | |
this.initialize.apply(this, arguments); | |
}; | |
StringBuilder.prototype = { | |
_nl: '\r\n', | |
_buf: null, | |
/** | |
* 初期化します。 | |
*/ | |
initialize: function() { | |
this._buf = []; | |
}, | |
/** | |
* 文字列を末尾に追加します。 | |
* @param value 追加する文字列。 | |
*/ | |
append: function(value) { | |
this._buf[this._buf.length] = value; | |
return this; | |
}, | |
/** | |
* 書式付き文字列を末尾に追加します。単純な置換処理のみ実装します。 | |
* @param format 書式付文字列 | |
* @param args 書式指定する文字列。 | |
*/ | |
appendFormat: function(format/*, args*/) { | |
if (!arguments || arguments.length <= 1) return; | |
var args = this._toArray(arguments).slice(1); | |
this._buf[this._buf.length] = format.replace(/\{(\d+)\}/g, function(match, index, offset, s) { | |
return args[index].toString(); | |
}); | |
return this; | |
}, | |
/** | |
* 文字列と行終端記号を末尾に追加します。 | |
* @param value 追加する文字列。 | |
*/ | |
appendLine: function(value) { | |
return this.append(value + this._nl); | |
}, | |
/** | |
* 追加した文字列を消去します。 | |
*/ | |
clear: function() { | |
this._buf = []; | |
return this; | |
}, | |
/** | |
* 追加された文字列全てを返します。 | |
*/ | |
toString: function() { | |
return this._buf.join(''); | |
}, | |
/** | |
* 現在の文字列の長さ (文字数)を取得します。 | |
*/ | |
length: function() { | |
return this.toString().length; | |
}, | |
/** | |
* argumentsオブジェクトを配列にして返します。 | |
* @param args argumentsオブジェクト | |
*/ | |
_toArray: function(args) { | |
if (!args || !args.length) return []; | |
var l = args.length, ret = new Array(l); | |
while(l--) { | |
ret[l] = args[l]; | |
} | |
return ret; | |
} | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment