[SOLVED] Lookup map functions being called during declaration

Issue

I am trying to implement a switch statement alternative using a map object and the functions that are supposed to be called according to the condition are being called while I’m declaring the map

Here is a simplified code of what I implemented

someMethodName(someParams, otherParams) {
  const verifyThis = callExternalApi(someParams);

  const customSwitch = {
    oneValue: this.doThis(otherParams),
    anotherValue: this.doThat(otherParams),
  };

  const possibleValues = ["oneValue", "anotherValue"];
  if (possibleValues.includes(verifyThis))
    return customSwitch[verifyThis];
  return this.defaultCase(otherParams);
}

I put a console.log in the methods to be called and found out that they are all being called, supposedly while I’m declaring customSwitch, and then one of the methods are being called when going through the if clause.

How do I work around this to avoid calling my methods?

Solution

Use an object whose values are functions which, when called, invoke the other functions:

const customSwitch = {
  oneValue: () => this.doThis(otherParams),
  anotherValue: () => this.doThat(otherParams),
};

and invoke when returning by doing

return customSwitch[verifyThis]();

Answered By – CertainPerformance

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *