string-repeat.js 726 B

123456789101112131415161718
  1. 'use strict';
  2. var global = require('../internals/global');
  3. var toIntegerOrInfinity = require('../internals/to-integer-or-infinity');
  4. var toString = require('../internals/to-string');
  5. var requireObjectCoercible = require('../internals/require-object-coercible');
  6. var RangeError = global.RangeError;
  7. // `String.prototype.repeat` method implementation
  8. // https://tc39.es/ecma262/#sec-string.prototype.repeat
  9. module.exports = function repeat(count) {
  10. var str = toString(requireObjectCoercible(this));
  11. var result = '';
  12. var n = toIntegerOrInfinity(count);
  13. if (n < 0 || n == Infinity) throw RangeError('Wrong number of repetitions');
  14. for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) result += str;
  15. return result;
  16. };