Problem
say that:
var stringToTest = "Hello i am walking"
And
var searchText = "Hello walking"
I have the following javascript function for filtering
.
var searchSplit = searchText.split(" ");
var num_split = searchSplit.length;
var correctTested = 0;
searchSplit.forEach(function (testString) {
if (stringToTest.indexOf(testString) >= 0) {
correctTested++;
}
});
//Decides if the value are close enough
if (correctTested > 0) {
var percentageCorrect = correctTested / num_split * 100;
return percentageCorrect >= 50;
}
else {
return false;
}
I have never done anything like this and i would like if you would rate or even come with suggestions on how to improve the above code.
Solution
My suggestions are mostly focused on making the code as concise and clear as possible.
-
Simplify the return statement.
if (correctTested > 0) { var percentageCorrect = correctTested / num_split * 100; return percentageCorrect >= 50; } else { return false; }
can be reduced to
return correctTested >= num_split * 0.5;
This eliminates both the condition as well as concern about div by 0.
-
Since you do not need a post-increment, choose pre-increment.
++correctTested
orcorrectTested += 1
rather thancorrectTested++
. -
Choose clear names.
searchSplit
might be clearer assearchTokens
,correctTested
asmatchedTokens
,num_split
astokenCount
. -
Consistent names.
searchCase
is camel case whilenum_split
is snake case. -
You have not articulated the functional spec, but consider whether the search should be case-insensitive. Also consider whether partial word matches are in fact acceptable or whether you require full token matches.
For ease of testing and for the ability to add different decision criteria you could consider decomposing match counting and the decision criteria into two separate functions.