Last active
August 29, 2015 14:17
-
-
Save huttj/fbe05e415b7f5974c44a to your computer and use it in GitHub Desktop.
indexOf
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
function indexOf(haystack, needle) { | |
// If either is undefined, quit | |
if (!haystack || !needle) return -1; | |
for (var i = 0; i < haystack.length; i++) { | |
// If there's not enough chars left in | |
// `haystack` for a match, quit | |
if (haystack.length - i < needle.length) return -1; | |
// Starting at the current index in `haystack`, iterate | |
// over the chars in `needle`, comparing against `haystack` | |
for (var j = 0; j < needle.length; j++) { | |
// If a char in `needle` doesn't match the char in | |
// `haystack`, break, going to the next char in `needle` | |
if (haystack[i+j] !== needle[j]) break; | |
// Otherwise, there is a match; if we're at the end of | |
// `needle`, we've matched all the chars from `needle`, | |
// so return the current index from `haystack` | |
if (j+1 === needle.length) return i; | |
} | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment