repeat() ๋ฉ์๋๋ ํธ์ถ๋ ๋ฌธ์์ด์์ ์ฌ๋ณธ์ด ํฌํจ. ์ฐ๊ฒฐํ์ฌ ์ง์ ๋ ํ์์ ์ ๋ฌธ์์ด์ ๊ตฌ์ฑํ๊ณ ๋ฐํํ๋ค.
const str = '๊ณ ์์ฐ ๋๋ฌด ๊ท์ฝ์ฐ ';
str.repeat(2); // "๊ณ ์์ฐ ๋๋ฌด ๊ท์ฝ์ฐ ๊ณ ์์ฐ ๋๋ฌด ๊ท์ฝ์ฐ "
์ฃผ์ด์ง ๋ฌธ์์ด์ ์ง์ ๋ ์์ ์ฌ๋ณธ์ ํฌํจํ๋ ์๋ก์ด ๋ฌธ์์ด
'abc'.repeat(-1); // RangeError: Invalid count value at String.repeat
'abc'.repeat(0); // ''
'abc'.repeat(1); // 'abc'
'abc'.repeat(2); // 'abcabc'
'abc'.repeat(3.5); // "abcabcabc" count๋ฅผ ์ ์๋ก ๋ณํ๋จ
'abc'.repeat(1/0); // RangeError: Invalid count value at String.repeat
({ toString: () => 'abc', repeat: String.prototype.repeat }).repeat(2); // "abcabc" repeat() generic method ์ด๋ค?
repeat๋ ECMAScript 2015 ๋ช
์ธ์ ์ถ๊ฐ๋์๋ค.
if (!String.prototype.repeat) {
String.prototype.repeat = function(count) {
'use strict';
if (this == null) {
throw new TypeError('can\'t convert ' + this + ' to object');
}
var str = '' + this;
count = +count;
if (count != count) count = 0;
if (count < 0) throw new RangeError('repeat count must be non-negative');
if (count == Infinity) throw new RangeError('repeat count must be less than infinity');
count = Math.floor(count);
if(str.length == 0 || count == 0) return '';
// count๊ฐ 31๋นํธ ์ ์์ธ์ง ํ์ธํ๋ฉด main part๋ฅผ ํฌ๊ฒ ์ต์ ํ ํ ์ ์๋ค.
// ๊ทธ๋ฌ๋ ๋๋ถ๋ถ์ ์ต์ (2014๋
8์) ๋ธ๋ผ์ฐ์ ๋ ๋ฌธ์์ด 1 << 28 ์ ์ด์์ ์ฒ๋ฆฌํ ์ ์์ผ๋ฏ๋ก
// ๋ค์๊ณผ ๊ฐ์ด ํด์ผํ๋ค.
if (str.length * count >= 1 << 28) {
throw new RangeError('repeat count must not overflow maximum string size');
}
var maxCount = str.length * count;
count = Math.floor(Math.log(count) / Math.log(2));
while(count) {
str += str;
count--;
}
str += str.substring(0, maxCount - str.length);
return str;
}
}