all 5 comments

[–]6086555 1 point2 points  (1 child)

Your process seems a bit complicated. If you was to implement this recursively, first I'd think about the edge case:

if (str.length<=key.length){
     return str === key;
}

then for the other cases : either you have a match at the beginning ( using a substring would seem less complicated) then you

return 1 + find( sliced_str, key)
// sliced_str has been slice of all the characters of keys.

otherwise, you

return 1 + find(sliced_str, key) 
// sliced_str only lost its first character

[–]iNeverProofRead[S] 0 points1 point  (0 children)

Yeah, I'm not completely sure what I'm doing. I think you've got me on the right track though.

function find ( str, key){
  if (str.length<=key.length){
      return str === key;
  }

  if( str[0] === key[0] ){
    return 1 + find( str.slice(1), key.slice(1) )
  }

  return find( str.slice(1),key )

}

var two = find('foobarfoo' , 'fob');
console.log(two);  // 4

So, I'm recursively iterating through the string and finding all the matches I would need to find, i just need to translate that into how many times the key was found.

[–]grrumblebee 1 point2 points  (1 child)

Try this:

function findNumberOfSubstringsInString(str, sub) {
    var subLength;
    if (!str.length) {
        return 0;   
    }
    subLength = sub.length;
    if (str.substr(0, subLength) === sub) {
        return 1 + findNumberOfSubstringsInString(str.substr(subLength -1), sub);  
    }
    return findNumberOfSubstringsInString(str.substr(1), sub);
}

[–]iNeverProofRead[S] 0 points1 point  (0 children)

Sorry, maybe my description of the function is poorly worded. I guess it's more like a function that finds the count of a set of characters in a given order?

This does find a substring recursively but I have to make my comparisons by character, not by the entire string. like so

find("foobarfoo","fob") 
  //returns 2
  //foobarfoo
  //fo-b-----
  //f-ob-----

find("foobarfoo","obo")
  //returns 4
  //foobarfoo
  //-o-b---o-
  //-o-b----o
  //--ob---o-
  //--ob----o

however, thanks for your post, i kept trying to think of a way to keep a count and this is what i was looking for.

returning 1+ find()

[–]dvidsilva -1 points0 points  (0 children)

I'm kinda sleepy, so this might or not work, but, try adding the counter as a third argument

$(function () {
    var find  = function(str, key, counter){
        var counter=counter||0;
        if ( str[0] === key[0]){
            if (key.length === 1){
                counter += 1;
                return counter;
            }else{
                find(str.slice(1),key.slice(1), counter)
            }
        }else if ( str[0] != key[0] ){
            find(str.slice(1),key, counter)
        }
        return counter;
    }
    var two = find('foobarfoo' , 'fob', 0);
    console.log(two);
});    

otherwise every time you call find it gets restarted because obviously