2008年 01月 08日

文字列の繰り返し

ref. http://d.hatena.ne.jp/higeorange/20080107/1199710820

String.prototype.repeat = function (n, sep) {
	if (n < 1) return "";
	return Array(n).join(this + (sep || "")) + this;
};

print("hoge".repeat(-1, '+')); //=> ""
print("hoge".repeat(0, '+'));  //=> ""
print("hoge".repeat(1, '+'));  //=> "hoge"
print("hoge".repeat(3, '+'));  //=> "hoge+hoge+hoge"
print("fuga".repeat(4, '-'));  //=> "fuga-fuga-fuga-fuga"
print("foo".repeat(4));        //=> "foofoofoofoo"