StringIndexOf.js 1.0 KB

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