igortp
igortp

Reputation: 179

Change method in a statement conditionally

Is possible to change a method according to the input without the need to duplicate a function? For example, if the variable intent assumes the value payment, the method applied to the object stripe is paymentIntents. If intent is setup, then the method applied to the object stripe is setupIntent

let intent = req.userIntent

stripe.paymentIntents.update("teste")

What I wouldn't like to do is:

let intent = req.userIntent

if (intent = "payment") {
     stripe.paymentIntents.update("teste")      
   } else if (intent = "setup") {  
     stripe.setupIntents.update("teste")
 }

Clarifying, the code is way bigger, but the same for both situations, except by the method (paymentIntents or setupIntent), and I don't want to repeat the code.

Upvotes: 1

Views: 63

Answers (3)

danh
danh

Reputation: 62686

Is the idea to economize on repeated code? You can build the stripe-calling the function from the string...

function makeAStripeFN(intent) {
  return new Function(`return stripe.${intent}Intents`);
}

Use it like this...

makeAStripeFN(req.userIntent)().update("teste")

Proving it with a mock stripe object...

class MockStripe {
  get paymentIntents() {
    console.log('called paymentIntents')
    return this
  }
  get setupIntents() {
    console.log('called setupIntents')
    return this
  }
  update(string) {
    console.log(`called update with '${string}'`)
  }
}
let stripe = new MockStripe()

function makeAStripeFN(intent) {
  return new Function(`return stripe.${intent}Intents`);
}

// 'payment' and 'setup' are values taken by req.userIntent

makeAStripeFN('payment')().update("teste")
console.log('\n')
makeAStripeFN('setup')().update("teste")

Upvotes: 0

kind user
kind user

Reputation: 41913

You could create a helper object that will hold proper key related to user input.

const o = {
   payment: 'paymentIntents',
   setup: 'setupIntents',
};

let intent = req.userIntent;

const o = {
   payment: 'paymentIntents',
   setup: 'setupIntents',
};

stripe[o[intent]].update("teste");

Note: You can extend the helper object with new fields to fit your needs.

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 371193

You can use the conditional operator in combination with bracket notation:

const prop = intent === 'payment'
  ? 'paymentIntents'
  : intent === 'setup'
    ? 'setupIntents'
    : null;
stripe[prop]?.update("teste");

or, you may be able to do

stripe[intent + 'intents']?.update("teste");

Note that = is assignment, not comparison. You want === to compare, not =.

If the intent can be only 'payment' or 'setup', it's easier:

stripe[intent === 'payment' ? 'paymentIntents' : 'setupIntents'].update("teste");

or

stripe[intent + 'intents'].update("teste");

Upvotes: 0

Related Questions