DEV Community

Cover image for Conditional Function Invocation without Conditional Statements in JS
Daniel Sasse
Daniel Sasse

Posted on

Conditional Function Invocation without Conditional Statements in JS

Reminiscing of Ruby's .send

Since I have begun exploring the world of Javascript and React in recent weeks, one of the things I have missed from the world of Ruby has been the .send method. Being able to call a method by way of a string or symbol argument (that could be stored in a variable) opens many doors for abstraction.

For those who are unfamiliar with Ruby's send method, I discuss it more in this blog post, but the gist of it can be seen below...(get it?)

While the amazingness of this may not be immediately apparent, I'll quickly reuse one of the example from the blog linked above. Here we are taking an array of instances, and are looking to create a new hash where the keys are specific property values of the instances, and the value for each key is the number of instances that have that property. There are a variety of ways to do this, but without send you would need two separate methods to perform this action for two different properties, however with send and the ability to pass in a string value that matches a property, we are able to use the same method for two different properties.


Enter the world of Javascript

As I dive in to Javascript, I love how it allows you to store functions as variables and pass functions as arguments, however for a while it still felt like something was missing, since I was struggling to find a way to conditionally invoke functions without the unnecessary complications of if... or switch statements.

Recently I came up with a solution, capitalizing on Javascript's ability to store functions as values in an Object while working on the problem below:

In a project, I was provided access to a Log class that took in a string and output the string as a log message object that contained the message type (error, warn,notify), the timestamp, and the message text:

Immediately I felt the single silent tear and pang of nostalgia for Ruby's send once again. How nice would it be to be able to invoke the correct function by just including the message type as a string along with the message test!

Log.send("warn")(message_text)
Enter fullscreen mode Exit fullscreen mode

The Solution

While typing the same statement into my text editor wishfully pretending JS has learned to be as fluffy as Ruby in the last few days, I realized "warn" in this case could also essentially be thought of as a key in an object, and JS DOES have the ability to process variables to use their values in selecting a key:

Since JS ALSO has the ability to store functions as keys in an object, this means that the three Log class methods that were defined earlier can each individually be stored into a logGenerator object under different keys. Any variable containing a string can then be passed to the object to load the desired function, and then invoke it with the desired arguments without the need for messy conditionals. See the comparison below:

As the conditional logic becomes for complex, or the number of possible values for the variable increase, the need for such a simple way to access a multitude of different functions becomes even clearer. Store the functions in an object, and use a variable to target the key of the function you wish to invoke.

Top comments (2)

Collapse
 
webketje profile image
webketje • Edited

Object.keys makes the LogGenerator completely obsolete:

const msg = { type: 'notify', text: 'Hello World' };
Object.keys(Log)[msg.type](msg.text);
Enter fullscreen mode Exit fullscreen mode

as

class Log {
  static notify() {
    ...
  }
}
Enter fullscreen mode Exit fullscreen mode

is really just syntactic sugar for

function Log() {}
Log.notify = function() { ... }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dsasse07 profile image
Daniel Sasse

Thank you for the insight! I haven't had any experience with Object.keys() before, and my use of Class syntax in JS so far is still limited.

Thank you for the suggestion.