This is our first pass at refactoring the code.
The code is reduced by 11 lines and quality issue
are improved.
You may want to
for reference
The changes to note are:
The string to work on is passed as an argument decoupling
the function and the source of the string.
All the variables have been declared with var.
Most of the declarations are at the top of the function, which is NOT
required in JavaScript, but.... For the rationale, I recommend Steve McConnells
book Code Complete. Some are initialized when declared,
but it is not necessary. It may be better to initialize
variables just before using them.
The value from charAt is stored in the variable char.
This improves performance and makes the following if test simpler.
count on line 11 is incremented when it's used
with the increment (++) operator.
On line 29, the conditional operator is used to
to set the value of incr. Compare this
to lines 31-35 of the original.
It may not be clear that line 30 of the original code and line 28
of the refactored code converts the sentence into an array of words.
Lines 31-35 (original 37-41) capitalize the first word, and the
following for-loop makes all subsequent words lower case.
That 7 line loop is reduced to 3 lines, and will be eliminated in
the next refactoring.
There are some small changes to the code that converts the array,
temp, into a string
On lines 25 and 46, charAt replaces the substring method
originally used. charAt is cleaner for getting one
character in a specific position. And slice on line 47
is cleaner to retrieve the remainder of the line.
Finally, the resulting string is returned instead of being assigned to
the field.
That covers some performance and coding quality,
but there are still some issues and it's 50 lines
while 18 was promised. So let's refactor again.