↑
Main Page
comparison function generator
<td>Smith</td>
<td>John</td>
</tr>
<tr>
<td>Johnson</td>
<td>Betty</td>
</tr>
<tr>
<td>Henderson</td>
<td>Nathan</td>
</tr>
<tr>
<td>Williams</td>
<td>James</td>
</tr>
<tr>
<td>Gilliam</td>
<td>Michael</td>
</tr>
<tr>
<td>Walker</td>
<td>Matthew</td>
</tr>
</tbody>
</table>
Of course, the functions from the previous section only worked with one column, so modifications are
needed.
The comparison function generator
Earlier in the book, it was mentioned that functions are just like any other type in JavaScript, meaning
that they can be passed as arguments to other functions or returned as a function value. In this chapter,
you have already seen a function passed to another function (the
sort()
method); now it’s time to look
at a function that returns a function.
The major limitation of the comparison function is its acceptance of two — and only two — arguments,
meaning that additional information can’t be passed in. To get around this, you can create a comparison
function generator, which is a separate function that returns a comparison function.
Because the
compareTRs()
must know which the column’s values to compare, it is necessary to pass in
an additional argument: the index of the column to act on. Using a comparison function generator, it’s
possible to pass this extra value into the comparison function:
function generateCompareTRs(iCol) {
return function compareTRs(oTR1, oTR2) {
var sValue1 = oTR1.cells[iCol].firstChild.nodeValue;
var sValue2 = oTR2.cells[iCol].firstChild.nodeValue;
return sValue1.localeCompare(sValue2);
};
}
374
Chapter 12
15_579088 ch12.qxd 3/28/05 11:40 AM Page 374
Free JavaScript Editor
Ajax Editor
©
→