StringLastIndexOf.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. 'use strict';
  2. var $TypeError = require('es-errors/type');
  3. var substring = require('./substring');
  4. var isInteger = require('../helpers/isInteger');
  5. // https://262.ecma-international.org/16.0/#sec-stringlastindexof
  6. module.exports = function StringLastIndexOf(string, searchValue, fromIndex) {
  7. if (typeof string !== 'string') {
  8. throw new $TypeError('Assertion failed: `string` must be a string');
  9. }
  10. if (typeof searchValue !== 'string') {
  11. throw new $TypeError('Assertion failed: `searchValue` must be a string');
  12. }
  13. if (!isInteger(fromIndex) || fromIndex < 0) {
  14. throw new $TypeError('Assertion failed: `fromIndex` must be a non-negative integer');
  15. }
  16. var len = string.length; // step 1
  17. var searchLen = searchValue.length; // step 2
  18. if (!((fromIndex + searchLen) <= len)) {
  19. throw new $TypeError('Assertion failed: fromIndex + searchLen ≤ len'); // step 3
  20. }
  21. for (var i = fromIndex; i >= 0; i--) { // step 4
  22. var candidate = substring(string, i, i + searchLen); // step 4.a
  23. if (candidate === searchValue) {
  24. return i; // step 4.b
  25. }
  26. }
  27. return 'NOT-FOUND'; // step 5
  28. };