- #1
Jamin2112
- 986
- 12
As you may have figured out, I'm obsessed with spending exorbitant amounts of time making optimizations to my code. Can anyone help me cut down on the number of comparisons in the following text2words function? The intent of the function should be easy to figure out from the comments.
Code:
function is_letter(c)
{
/* Returns whether a character c is in the set {'a', 'b', ..., 'z', 'A', 'B', ..., 'Z'}
*/
return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));
}
function text2words(S)
{
/* Given a string S, return an array A of all the words
in S, a word being defined as a sequence of consecutive
characters in the set {'a', 'b', ..., 'z', 'A', 'B', ..., 'Z'}.
*/
var A = new Array();
var thisword = new String();
var i = 0, j = S.length;
while (i < j)
{
if (is_letter(S[i]))
{
while (i < j && is_letter(S[i]))
thisword += S[i++];
A.push(thisword);
thisword = "";
}
else
{
++i;
}
}
return A;
}