0

I have an object and 3 methods, now my code to execute it looks like this:

var cmpAmount = 50,
    addLessAmount = 6,
    addMoreAmount = 14;
priceChanger.changeSmallPrice(cmpAmount, addLessAmount, addMoreAmount);
priceChanger.changeBigPrice(cmpAmount, addLessAmount, addMoreAmount);
priceChanger.changeTooltipPrice(cmpAmount, addLessAmount, addMoreAmount);

so, if arguments are the same how to execute it three with sending them the parameters. I mean how to change my code to make it less.

3
  • May be there is something wrong in your code, I guess not following the DRY principle. Commented Feb 2, 2014 at 19:57
  • 1
    priceChanger.changeAllPrices? Commented Feb 2, 2014 at 19:57
  • How about creating one function in your object that executes the other three, just pass the arguments array along. Commented Feb 2, 2014 at 19:59

3 Answers 3

1

I think it would be best to make a method "changeAllPrices(cmpAmount, addLessAmount, addMoreAmount)"

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

Comments

0

Maybe using a object to store all properties :

var args = {cmpAmount:50,addLessAmount: 6, addMoreAmount: 14};

priceChanger.changeSmallPrice(args);
priceChanger.changeBigPrice(args);
priceChanger.changeTooltipPrice(args);

Comments

0

You can use a simple helper function, such as the one below, to call each function with an array of arguments. I believe some javascript libraries include a similar composition function called composeArgs

function execute(fns, args) {
   for(var i = 0; i < fns.length; i++) {
       fns[i].apply(this, args);
   }
}

Then call execute

var cmpAmount = 50,
    addLessAmount = 6,
    addMoreAmount = 14;

execute([priceChanger.changeSmallPrice, priceChanger.changeBigPrice, priceChanger.changeTooltipPrice], 
        [cmpAmount, addLessAmount, addMoreAmount]);

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.