Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Lookup map functions being called during declaration

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading