Main Page

Modifying the code

“string”
, the returned value is a string and
typeof
returns
“string”
. A string is also returned when
the second argument is omitted and when the second argument is
“football”
.
With the conversion function complete, you must modify the rest of the code to use it.
Modifying the code
The first step is to modify the
generateCompareTRs()
function, which now must accept an additional
argument indicating the data type to use when comparing values. Then, the values from the table must
be converted into the appropriate data type within the comparison function:
function generateCompareTRs(iCol, sDataType) {
return function compareTRs(oTR1, oTR2) {
var vValue1 = convert(oTR1.cells[iCol].firstChild.nodeValue,
sDataType);
var vValue2 = convert(oTR2.cells[iCol].firstChild.nodeValue,
sDataType);
//...
};
}
This change to
generateCompareTRs()
once again takes advantage of JavaScript’s support of closures,
passing the
sDataType
argument directly into the comparison function. Unfortunately, you can no
longer use the
localeCompare()
method to return the appropriate function value because numbers
and dates don’t support it. Because you can’t be sure which type of value is being stored, and it doesn’t
make sense to handle each data type’s comparisons differently, it’s best just to use less-than and greater-
than to determine which value to return:
function generateCompareTRs(iCol, sDataType) {
return function compareTRs(oTR1, oTR2) {
var vValue1 = convert(oTR1.cells[iCol].firstChild.nodeValue,
sDataType);
var vValue2 = convert(oTR2.cells[iCol].firstChild.nodeValue,
sDataType);
if (vValue1 < vValue2) {
return –1;
} else if (vValue1 > vValue2) {
return 1;
} else {
return 0;
}
};
}
It may not always be necessary to distinguish between integer and floating-point
values when sorting. Most of the time, simply converting all numbers to floating-
point is sufficient. The code in this chapter uses both types of numbers for illustra-
tive purposes only.
379
Sorting Tables
15_579088 ch12.qxd 3/28/05 11:40 AM Page 379


JavaScript EditorFree JavaScript Editor     Ajax Editor


©