0

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.

3
  • Do you really want to make this code even less readable? Commented Jul 9, 2012 at 15:16
  • I find it quite readable; what's not clear? Commented Jul 9, 2012 at 15:16
  • It is now, but will it be if you use those answers? Commented Jul 9, 2012 at 15:19

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Too bad you even loose more context this way. Now you got SomeVar, having an Integer value, referring to an anonymous function X that apparently sorts in some way... Of course you can comment your code, but then you still got the same number of lines you got in the first place, only less readable.
Can I keep the function's in the array name?
@GolezTrol — Well yes, see the last paragraph of the answer.
@GolezTrol — I edited in the advice about 30 seconds after answering the question.
ok, I left the arrays without the function name and to keep the code easy to understand, I just added the name of the function as a comment. Thanks
3

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];
};

1 Comment

+1 for providing code that shows at least a little clarity by itself.
1

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.