Javascript String 함수중에서 String.prototype.indexOf()를 구현하는 문제
찾고자하는 값이 비어있을때는 0을 반납한다.
haystack
문자열을 순서대로 비교하면서 needle
의 문자열과 일치하는지 두 반복문을 이용해서 비교한다.
haystack
이 남은 문자열수가 needle
보다 적지않도록 조건을 준다.haystack
에 needle
문자열이 존재하는 경우 현재 순환중인 haystack
의 인덱스를 리턴하고 존재하지않다면 -1을 리턴한다.
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function(haystack, needle) {
if (!needle.length) return 0
outer:for(let i = 0 ; i < haystack.length; i++) {
if (haystack.length - i < needle.length) break
for(let j = 0 ; j < needle.length; j++) {
if(haystack[j + i] !== needle[j]) continue outer
}
return i
}
return -1
};