Created
May 13, 2016 03:51
-
-
Save sashak007/d19a92207526f72e8cec53bb9c266ffa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} | |
} | |
} |
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
Another soultion -
Without using length.
Taken from
https://stackoverflow.com/questions/46731372/where-should-i-find-how-the-indexof-function-is-written-for-javascript-core-look