frenchie
frenchie

Reputation: 51937

javascript getting index of nested function within function

I have a function that sorts an array and within it, I have custom sort functions. Something like this:

function SortTheArray() {

  function SortCriteria1Asc(a, b) { ... }
  function SortCriteria1Dsc(a, b) { ... }
  function SortCriteria2Asc(a, b) { ... }
  function SortCriteria1Asc(a, b) { ... }

  var CustomSort;

  switch (SomeVar) {

     case 1:
       CustomSort = SortCriteria1Asc;
       break;

     case 2:
        CustomSort = SortCriteria1Dsc;
        break;

     case ....
  }

  SomeDataArray.sort(CustomSort);
}

Is it possible to remove the switch statement and say that the CustomSort function is simply equal to the nth nested function?

Thanks for your suggestions.

Upvotes: 0

Views: 72

Answers (3)

bokonic
bokonic

Reputation: 1771

Why don't you defined the inner functions in an object indexed by the variable you are switching by?

function SortTheArray(someVar){

   var sorters = {
       CriteriaA: function(array){ ... };
   };
   return sorters[someVar];
};

Upvotes: 3

Quentin
Quentin

Reputation: 943571

Don't give the function names, store them in an array.

var functions = [
  function (a,b) { ... },
  function (a,b) { ... },
  function (a,b) { ... }
];

Then just:

SomeDataArray.sort(functions[SomeVar]);

… but numerically indexed function identifiers don't sound like a very good idea. You would probably be better off using an object rather than array and giving them descriptive names.

Upvotes: 4

Denys Séguret
Denys Séguret

Reputation: 382150

You can simply build your functions directly in an array :

function SortTheArray() {
   var functions = [];
   functions.push(function(a,b) { ... });

Then you can execute functions[i](a,b).

Upvotes: 1

Related Questions