This challenge was pretty short, but it was fun to play with!
I hope you enjoy it!
Nice solution.
There’s just one thing. If a letter in word
is not found, you’ll still going to check the other letters but it’s not necessary.
Here’s my version which exits as soon as a letter is not found:
function occ2(str, word) {
let idx = 0;
for (let i=0,l=word.length; i<l; i++) {
// make sure we search after the previous letter by passing idx as second param
idx = str.indexOf(word[i], idx);
if (idx === -1) {
return false
}
idx++;
}
return true
}
You also do not need to split str
into an array as indexOf
is also available for String
objects.
Hope this helps.
Very nice solution @JoolsMcFly !
I just learned today I can pass a second argument for the indexOf method.
Thanks!
If you want, you could also post the answer in the comments section on medium. This way other readers can find it easily there too
You’re right. I’ll do that then. Cheers.
Found another shorter solution while stretching. You just never know when ideas pop, eh?
function Test (s, w) {
var pattern = w.replace(/./g, function(char) {
return char + '.*';
}).slice(0, -2); // remove trailing .*
return s.search(new RegExp(pattern)) !== -1;
}
I have not benchmarked it but it’s showcasing an alternative, non array-based approach.
To be honest RegExp is something I need to look into more
I’d love to write a follow up for the article with your code if you allow me to do so of course!
Thank you @JoolsMcFly for this amazing solution! I love it!
You can include both solutions, np.
Cool stuff, well presented.
One correction is needed though.
If the word is
medium
the pattern will be: w.*o.*r.*d.*
Pattern would be m.*e.*d.*i.*u.*m.*
in this case.
Onto the next one!
Thank you for the correction!