es.string.ends-with.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f;
  4. var toLength = require('../internals/to-length');
  5. var notARegExp = require('../internals/not-a-regexp');
  6. var requireObjectCoercible = require('../internals/require-object-coercible');
  7. var correctIsRegExpLogic = require('../internals/correct-is-regexp-logic');
  8. var IS_PURE = require('../internals/is-pure');
  9. // eslint-disable-next-line es/no-string-prototype-endswith -- safe
  10. var $endsWith = ''.endsWith;
  11. var min = Math.min;
  12. var CORRECT_IS_REGEXP_LOGIC = correctIsRegExpLogic('endsWith');
  13. // https://github.com/zloirock/core-js/pull/702
  14. var MDN_POLYFILL_BUG = !IS_PURE && !CORRECT_IS_REGEXP_LOGIC && !!function () {
  15. var descriptor = getOwnPropertyDescriptor(String.prototype, 'endsWith');
  16. return descriptor && !descriptor.writable;
  17. }();
  18. // `String.prototype.endsWith` method
  19. // https://tc39.es/ecma262/#sec-string.prototype.endswith
  20. $({ target: 'String', proto: true, forced: !MDN_POLYFILL_BUG && !CORRECT_IS_REGEXP_LOGIC }, {
  21. endsWith: function endsWith(searchString /* , endPosition = @length */) {
  22. var that = String(requireObjectCoercible(this));
  23. notARegExp(searchString);
  24. var endPosition = arguments.length > 1 ? arguments[1] : undefined;
  25. var len = toLength(that.length);
  26. var end = endPosition === undefined ? len : min(toLength(endPosition), len);
  27. var search = String(searchString);
  28. return $endsWith
  29. ? $endsWith.call(that, search, end)
  30. : that.slice(end - search.length, end) === search;
  31. }
  32. });