I want to extend Array.sort() to accept another parameter. This question has a solution using a closure, so this code works:
var create_comparator = function(c) {
return function(a,b) { console.log(c); return a-b };
};
arr.sort( create_comparator('test') );
However, in my case I have functions already defined like this:
var myComp1 = function(a,b) { console.log(c); return a-b };
Returning the pre-defined function doesn't work:
var create_comparator = function(sortfn, c) {
// Uncaught ReferenceError: c is not defined
return sortfn;
};
var arr = [7, 4, 9, 2, 1];
arr.sort( create_comparator(myComp1, 'test') );
I presume that's because c
wasn't defined when the original function was created. I tried return function(a,b) { sortfn(a,b); }
to create a new closure but that doesn't work either.
Is it possible, using this set-up, for extra parameters to be available to the pre-defined function? Is there another solution for the problem?