One thing you can do is use closure to hide the configuration parameter passed from the user:
var mk_mover = function(direction){ return function(){
If you want to continue work in this direction, basically solve the question of how best to pass the parameters of the overall implementation, and there is no single best solution for this.
One of the possible directions is to use the OO style approach, passing the object of the strategy โstrategyโ to the implementation function.
var mk_mover = function(args){ var get_item = args.getItem, ins_next = args.insNext; return function(){ var next = get_item.call(this); next && ins_next.call(this, next); }; }; var move_up = mk_mover({ get_item : function(){ return this.getPrevious(); }, get_next : function(x){ return this.insertBefore(x); } }); var move_down = mk_mover({});
I prefer to do this when the strategy interface (methods that differ from each other) is small and relatively constant, and when you want to open up the possibility of adding new kinds of directions in the future.
I also use this when I know that neither the set of directions nor the methods should change much, since JS supports OO better than for switch statements.
Another possible direction is the enumeration approach you used:
var mk_mover = function(direction){ return function(){ var next = ( direction === 'up' ? this.getNextItem() : direction === 'down' ? this.getPreviousItem() : null ); if(next){ if(direction === 'up'){ this.insertAfter(next); }else if(direction === 'down'){ this.insertBefore(next); } }
Sometimes you can use neat objects or arrays instead of switch statements to make things prettier:
var something = ({ up : 17, down: 42 }[direction]);
Although I have to admit that this is rather clumsy, it has the advantage that if your set of directions is fixed at an early stage, you now have many options to add a new if-else or switch statement when you need it offline ( without having to add some methods to the strategy object somewhere else ...)
By the way, I think that the approach you proposed sits in an uncomfortable middle between the two versions that I proposed.
If everything you do switches inside your function depending on the value direction tag passed in, itโs best to just switch directly to the spots you need so as not to redo things into separate functions and then do a lot of annoying .call and .plply .
On the other hand, if you are faced with the problem of defining and separating functions, you can do it in such a way that you simply receive them directly from the caller (in the form of a strategy object) instead of manually scheduling them yourself.