Pages

Sunday, January 29, 2012

strstr (JavaScript)

So I ran across this post and I was curious if I could write my own strstr function without using any library calls, just arrays, but in javascript. 15 minutes later and voila it works! Here it is:
function strstr(haystack, needle) {
    var i = 0,
        tempLength = 0,
        temp = [];
    for (;;) {
        if (haystack[i] === undefined || needle == null) {
            return "No match";
        }
        //if the char doesn't match then reset
        else if (haystack[i] !== needle[tempLength]) {
            temp = [];
            tempLength = 0;
        }
        //the char matches so let's store it.
        else if (haystack[i] === needle[tempLength]) {
            temp[tempLength] = haystack[i];
            if (needle[tempLength + 1] === undefined) {
                return temp;
            }
            tempLength++;
        }
        i++;
    }
};

No comments:

Post a Comment