After staring at your code for some time,
- You are using Hungarian notation, that is not a JavaScript practice
- Related to that,
strArr
probably should have beenarrStr
if the code was consistent
- Related to that,
- It seems odd that you would return
0
when either word is not present,0
would indicate that the words are neighbours. I would return -1 in that case. - You seem to track too much state in
acc
, you can get away with just tracking the last matched word, the location of the last matched word and what the best distance has been thus far - There are no comments whatsoever, I think your code could have used some
This is my functional approach:
const s = "dog cat hello cat dog dog hello cat dog world dog hello";
function smallestWordDistance(s, w1, w2) {
function analyze(acc, word, index) {
if (word == w1 || word == w2) {
if (acc.word && acc.word != word) {
letconst distance = index - acc.index - 1;
acc.out = acc.out == -1 ? distance : Math.min(acc.out, distance);
}
acc.index = index;
acc.word = word;
}
return acc;
}
return s.split(' ').reduce(analyze, { out: -1 }).out;
}
console.log(smallestWordDistance(s, "hello", "world"));