Improve String.repeat.

Adapted from patch contributed by Isiah Meadows <impinball@gmail.com>.

R=jkummerow@chromium.org

Review URL: https://codereview.chromium.org/657863002

git-svn-id: https://v8.googlecode.com/svn/branches/bleeding_edge@24687 ce2b1a6d-e550-0410-aec6-3dcde31c8c00
This commit is contained in:
yangguo@chromium.org 2014-10-17 10:01:38 +00:00
parent f0e3ae8e24
commit d913faaf6d
3 changed files with 13 additions and 6 deletions

View File

@ -39,6 +39,7 @@ Fedor Indutny <fedor@indutny.com>
Filipe David Manana <fdmanana@gmail.com>
Haitao Feng <haitao.feng@intel.com>
Ioseb Dzmanashvili <ioseb.dzmanashvili@gmail.com>
Isiah Meadows <impinball@gmail.com>
Jacob Bramley <jacob.bramley@arm.com>
Jan de Mooij <jandemooij@gmail.com>
Jay Freeman <saurik@saurik.com>

View File

@ -17,16 +17,19 @@ function StringRepeat(count) {
var s = TO_STRING_INLINE(this);
var n = ToInteger(count);
if (n < 0 || !NUMBER_IS_FINITE(n)) {
// The maximum string length is stored in a smi, so a longer repeat
// must result in a range error.
if (n < 0 || n > %_MaxSmi()) {
throw MakeRangeError("invalid_count_value", []);
}
var elements = new InternalArray(n);
for (var i = 0; i < n; i++) {
elements[i] = s;
var r = "";
while (true) {
if (n & 1) r += s;
n >>= 1;
if (n === 0) return r;
s += s;
}
return %StringBuilderConcat(elements, n, "");
}

View File

@ -61,8 +61,11 @@ assertEquals("", "".repeat(5));
assertEquals("", "abc".repeat(0));
assertEquals("abcabc", "abc".repeat(2.0));
assertEquals("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "a".repeat(37));
assertThrows('"a".repeat(-1)', RangeError);
assertThrows('"a".repeat(Number.POSITIVE_INFINITY)', RangeError);
assertThrows('"a".repeat(Math.pow(2, 30))', RangeError);
assertThrows('"a".repeat(Math.pow(2, 40))', RangeError);
var myobj = {
toString: function() {