es.string.substr.js 1.2 KB

123456789101112131415161718192021222324252627282930
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var uncurryThis = require('../internals/function-uncurry-this');
  4. var requireObjectCoercible = require('../internals/require-object-coercible');
  5. var toIntegerOrInfinity = require('../internals/to-integer-or-infinity');
  6. var toString = require('../internals/to-string');
  7. var stringSlice = uncurryThis(''.slice);
  8. var max = Math.max;
  9. var min = Math.min;
  10. // eslint-disable-next-line unicorn/prefer-string-slice -- required for testing
  11. var FORCED = !''.substr || 'ab'.substr(-1) !== 'b';
  12. // `String.prototype.substr` method
  13. // https://tc39.es/ecma262/#sec-string.prototype.substr
  14. $({ target: 'String', proto: true, forced: FORCED }, {
  15. substr: function substr(start, length) {
  16. var that = toString(requireObjectCoercible(this));
  17. var size = that.length;
  18. var intStart = toIntegerOrInfinity(start);
  19. var intLength, intEnd;
  20. if (intStart === Infinity) intStart = 0;
  21. if (intStart < 0) intStart = max(size + intStart, 0);
  22. intLength = length === undefined ? size : toIntegerOrInfinity(length);
  23. if (intLength <= 0 || intLength === Infinity) return '';
  24. intEnd = min(intStart + intLength, size);
  25. return intStart >= intEnd ? '' : stringSlice(that, intStart, intEnd);
  26. }
  27. });