es.string.ends-with.js 1.6 KB

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