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;
}
}
}
}
@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