es.string.at-alternative.js 989 B

1234567891011121314151617181920212223242526
  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 fails = require('../internals/fails');
  8. var charAt = uncurryThis(''.charAt);
  9. var FORCED = fails(function () {
  10. // eslint-disable-next-line es/no-array-string-prototype-at -- safe
  11. return '𠮷'.at(-2) !== '\uD842';
  12. });
  13. // `String.prototype.at` method
  14. // https://github.com/tc39/proposal-relative-indexing-method
  15. $({ target: 'String', proto: true, forced: FORCED }, {
  16. at: function at(index) {
  17. var S = toString(requireObjectCoercible(this));
  18. var len = S.length;
  19. var relativeIndex = toIntegerOrInfinity(index);
  20. var k = relativeIndex >= 0 ? relativeIndex : len + relativeIndex;
  21. return (k < 0 || k >= len) ? undefined : charAt(S, k);
  22. }
  23. });