views:

43

answers:

2

Using the example below, is it possible to send the result of the callback function to the console, i.e. the value being returned?

rows.sort(function(a, b) {
 if(a.sortKey < b.sortKey) return -sortDirection;
 if(a.sortKey > b.sortKey) return sortDirection;
 return 0;
 });

What would I use as the argument: console.log(?)

+2  A: 

You could always log before you return, and refactor to support easy logging. Other than that, the return value is lost to the sort function.

rows.sort(function(a, b) {
 var returnVal = 0;
 if(a.sortKey < b.sortKey) returnVal = -sortDirection;
 else if(a.sortKey > b.sortKey) returnVal = sortDirection;

 console.log( returnVal );
 return returnVal;
 });
Stefan Kendall
A: 

You can always take advantage of functions being first class objects in Javascript, and play around with AOP-like wrapping:

function addLogging(fn){
  return function() {
    var result = fn.apply(null, arguments);
    console.log(result);
    return result;
  }
}

var sortDirection = 1;

[ {sortKey: 1}, {sortKey: 2}, {sortKey: 0} ].sort(addLogging(function(a, b){
  if(a.sortKey < b.sortKey) return -sortDirection;
  if(a.sortKey > b.sortKey) return sortDirection;
  return 0;
}));
kangax