mathiasbynens / String.prototype.repeat

A robust & optimized ES3-compatible polyfill for the `String.prototype.repeat` method in ECMAScript 6.
https://mths.be/repeat
MIT License
27 stars 7 forks source link

'x'.repeat(2**32) === '' #9

Open Yaffle opened 4 years ago

Yaffle commented 4 years ago

thanks to bitwise operators!

nicolo-ribaudo commented 4 years ago

Good catch!

I was writing a fix, but then realized that strings with 2**32 characters aren't supported by JS engines (even if the specified string limit is 2**53-1):

➜ eshost -t -e "'x'.repeat(2**32)"
┌────────────────┬──────────────────────────────────────────────────────────────────────────────────────────┐
│ ChakraCore     │                                                                                          │
├────────────────┼──────────────────────────────────────────────────────────────────────────────────────────┤
│ Hermes         │                                                                                          │
│                │ RangeError: String.prototype.repeat result exceeds limit                                 │
├────────────────┼──────────────────────────────────────────────────────────────────────────────────────────┤
│ JavaScriptCore │ [native code]                                                                            │
│                │ global code@/tmp/D5Afw4OOC1ITm5fb2Gug/f-1592774560118-35784-4qqzxn.4m9gn.js:1:445        │
│                │ RangeError: Out of memory                                                                │
├────────────────┼──────────────────────────────────────────────────────────────────────────────────────────┤
│ Moddable XS    │                                                                                          │
│                │ Error: Received unexpected signal: SIGSEGV                                               │
├────────────────┼──────────────────────────────────────────────────────────────────────────────────────────┤
│ SpiderMonkey   │                                                                                          │
│                │ RangeError: repeat count must be less than infinity and not overflow maximum string size │
├────────────────┼──────────────────────────────────────────────────────────────────────────────────────────┤
│ V8             │                                                                                          │
│                │ RangeError: Invalid string length                                                        │
└────────────────┴──────────────────────────────────────────────────────────────────────────────────────────┘

Even if we correctly divided 2**32 by two, it would still throw at the end. WDYT about explicitly throwing an (uncompliant) error?

Yaffle commented 4 years ago

throwing the error when count > 2**31-1, and the empty string should be handled separately in this case.