StringIndexOf.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var callBound = require('call-bind/callBound');
  4. var $TypeError = GetIntrinsic('%TypeError%');
  5. var IsIntegralNumber = require('./IsIntegralNumber');
  6. var Type = require('./Type');
  7. var $slice = callBound('String.prototype.slice');
  8. // https://ecma-international.org/ecma-262/12.0/#sec-stringindexof
  9. module.exports = function StringIndexOf(string, searchValue, fromIndex) {
  10. if (Type(string) !== 'String') {
  11. throw new $TypeError('Assertion failed: `string` must be a String');
  12. }
  13. if (Type(searchValue) !== 'String') {
  14. throw new $TypeError('Assertion failed: `searchValue` must be a String');
  15. }
  16. if (!IsIntegralNumber(fromIndex) || fromIndex < 0) {
  17. throw new $TypeError('Assertion failed: `fromIndex` must be a non-negative integer');
  18. }
  19. var len = string.length;
  20. if (searchValue === '' && fromIndex <= len) {
  21. return fromIndex;
  22. }
  23. var searchLen = searchValue.length;
  24. for (var i = fromIndex; i <= (len - searchLen); i += 1) {
  25. var candidate = $slice(string, i, i + searchLen);
  26. if (candidate === searchValue) {
  27. return i;
  28. }
  29. }
  30. return -1;
  31. };