Advertisement
binibiningtinamoran

CustomIndexOf.js

May 27th, 2019
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. // WRITE A CUSTOM INDEXOF METHOD
  3. // Write a naive version of the indexOf method.
  4. let customIndexOf = (str, searchChar, fromIndex) => {
  5.  
  6.     let found = false; // this will make the method efficient!
  7.  
  8.     for (let i = fromIndex, length = str.length; i < length && !found; i++) {
  9.         if (str[i] === searchChar) {
  10.             return i; // returns the position of the first occurrence of searchChr
  11.         }
  12.     }
  13.  
  14.     return -1;
  15. };
  16.  
  17. // Tests
  18. console.log(customIndexOf('vAnce','n',3)); // returns -1 since no n is found from index 3 till end of String
  19. console.log(customIndexOf('ccccat','c',0)); // returns 0 since c was found on index 0 and index 0 is within the range of the fromIndex
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement