Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sashak007/d19a92207526f72e8cec53bb9c266ffa to your computer and use it in GitHub Desktop.
Save sashak007/d19a92207526f72e8cec53bb9c266ffa to your computer and use it in GitHub Desktop.
// Correct Way
function indexOf(str, query) {
for(var i = 0; i < str.length; i++) {
for(var q = 0; q < query.length; q++) {
if (str[i+q] !== query[q]) {
break;
}
if (q === query.length - 1) {
return i;
}
}
}
return -1;
}
//Incorrect -- will result in -1 if query is more than one letter:
function indexOf(str, query) {
for(var i = 0; i < str.length; i++) {
for(var q = 0; q < query.length; q++) {
if (str[i+q] !== query[q]) {
break;
}
if (q === query.length - 1) {
return i;
} else {
return -1;
}
}
}
}
//Incorrect -- will result in -1 if any matches occur
function indexOf(str, query) {
for(var i = 0; i < str.length; i++) {
for(var q = 0; q < query.length; q++) {
if (str[i+q] !== query[q]) {
break;
}else {
return -1;
}
if (q === query.length - 1) {
return i;
}
}
}
}
@LiorA1
Copy link

LiorA1 commented Apr 2, 2021

Another soultion -

function strstr(str, query) {
  for (var j = 0; str[j]; j++)
  {
    var found = true;
    for (var i = 0; query[i]; i++) {
      if (str[j + i] !== query[i]) { found=false; break; }
    } 
    if (found) return j;
  }
  return -1;
}

var s = "CodefightsIsAwesome";
var x = "IA";

console.log(strstr(s, x));

s = "CodefightsIsAwesome";
x = "IsA";

console.log(strstr(s, x));

Without using length.

Taken from
https://stackoverflow.com/questions/46731372/where-should-i-find-how-the-indexof-function-is-written-for-javascript-core-look

@Momellouky
Copy link

Hello,
I guess there is a problem with the solution commented with // correct way.
If you don't test ( i + j ) < string.length, it may goes out of bound.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment